There's currently no function within the user module to check if a user has been assigned a certain role.

I usually need to do this on most sites that I work on, so I have to write a function within a custom module. As D8 has the User::hasRole method, it would be great to have an equivalent available in D7.

Comments

opdavies’s picture

Status: Active » Needs review
StatusFileSize
new686 bytes
opdavies’s picture

Title: Add a function to check for roles for a user » Add a function to check if a user has a certain role
misc’s picture

Status: Needs review » Reviewed & tested by the community

Tested and looks ok for me.

opdavies’s picture

@MiSc: Thanks for the review.

opdavies’s picture

StatusFileSize
new671 bytes

Updated the patch - isset() is faster.

opdavies’s picture

Status: Reviewed & tested by the community » Needs review

Setting back to "needs review" so that the testbot picks it up.

opdavies’s picture

This is once again ready for community review.

opdavies’s picture

Issue tags: +Novice
tobiberlin’s picture

Status: Needs review » Reviewed & tested by the community

Tested and works fine

opdavies’s picture

@tobiberlin: Thanks for the review!

David_Rothstein’s picture

Status: Reviewed & tested by the community » Fixed
Issue tags: +7.36 release notes

Sure, why not :) We could have tests for this, but given that it's basically a one-line function and isn't going to change, it's probably fine without them for now.

Committed to 7.x - thanks!

Fixed a couple documentation issues on commit:

--- a/modules/user/user.module
+++ b/modules/user/user.module
@@ -854,11 +854,11 @@ function user_is_blocked($name) {
  * @param int $rid
  *   A role ID.
  *
- * @param bool|object $account
+ * @param object|null $account
  *   (optional) A user account. Defaults to the current user.
  *
  * @return bool
- *   TRUE or FALSE.
+ *   TRUE if the user has the role, or FALSE if not.
  */
 function user_has_role($rid, $account = NULL) {
   if (!$account) {

  • David_Rothstein committed 5a17a54 on 7.x
    Issue #2394517 by opdavies: Add a function to check if a user has a...
opdavies’s picture

@David_Rothstein: Thanks for committing the patch, and for those documentation changes.

vijaycs85’s picture

awesome, don't we need a change notice?

David_Rothstein’s picture

Since it's just a new API function (and not something that means people really need to think about changing their existing code) I figured a release notes mention would be enough.

But if someone wants to write a change notice too, that would certainly be fine and I'd definitely link to it from the release notes.

vijaycs85’s picture

David_Rothstein’s picture

Looks good - thanks!

I published the change notice and will make sure it gets linked to from the release notes, etc.

rajab natshah’s picture

Testing :)

Rewarded work .

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.