0

how can I access to my user role thanks to my user custom field ?

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value.

Then, I need to check if this user as the role "director".

But I don't know how to access role thanks to another field.

EDIT :

See this loop :

foreach($retraitDoublons as $valUnique){
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['field_custVal' => $valUnique]);
  $user = reset($users);
  $user_has_role = $user && $user->hasRole('directeur_cr_');

  dump($user);
  dump($user_has_role);

  echo $valUnique . "<hr>";
}
0

Similar to this question:

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value:

$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['field_custField' => '123456']);

Then, I need to check if this user:

$user = reset($users);

has the role "director":

$user_has_role = $user && $user->hasRole('director');
  • This will work with the no current user (I forgot this part, I need this for not current user) – Morgan Tartreau Sep 4 '18 at 6:48
  • I'm afraid I can't follow, all users can't be a current user. I've inserted your question step-by-step. – 4k4 Sep 4 '18 at 7:01
  • See my updated answer please. Your code seems to work (because $user_has_role is returning true), but my loop is doing this only one time, even if there's several account related to this value. – Morgan Tartreau Sep 4 '18 at 7:27
  • Then you need to loop over $users. This is a PHP question and the code depends on what you want to do with the result. – 4k4 Sep 4 '18 at 7:30
  • According to your code, what should I change ? – Morgan Tartreau Sep 4 '18 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.