1

I want to assign newly created users to an editor role if their email domain name is @gmail.com and moderator role if their email suffix is @hotmail.com.

I have tried to do something like this in my .module file but with no luck.

/**
 * Implements hook_user_insert().
 */
function MODULENAME_user_insert($account) {
  $user = db_insert('user_changes');
  $user->fields(array('uid' => $account->id(), 'created' => time()))->execute();
  if($account->uid->maildomain == '@gmail.com') {
    $user->assignRole('editor')->execute();
  }
}

I found a link to how to use hook_user_insert() here. Because I thought that it maybe could do it, but I didn't find the solution.

  • 2
    I always thought the prefix would be the part left of the @ sign. For this question the term domain name would make more sense. – Neograph734 Sep 6 '17 at 14:23
  • If you want to get this question re-opened, you should at least show the exact code you are using. A module doesn't implement hooks with a function whose name is hook_user_insert(). Then, the code you are showing contains two syntax errors. – kiamlaluno Mar 25 '18 at 17:36
2

Please try this code in custom module.

function hook_user_insert($account) {
 $user = \Drupal\user\Entity\User::load($account->id());
 $user_email = $user->getEmail();
 $extension = explode('@',$user_email);
 if($extension[1] == 'gmail.com' ){
 $user->addRole('yourrolegmail');
 $user->save();
 }
 elseif($extension[1] == 'yahoo.com'){
 $user->addRole('yourroleyahoo');
 $user->save();
 }else{
 $user->addRole('yourrolenormal');
 $user->save();
 }
 }

Thanks

  • Yes hook_user_insert call when user insert in db.What you want ? – Pankaj Yogi Aug 15 '17 at 9:07
  • I tried to add a new user with a gmail and when I save the new user there is no role applied to the user. – Jdrupal Aug 15 '17 at 9:09
  • I want an editor role to be added if the new user has a gmail. – Jdrupal Aug 15 '17 at 9:10
  • Are you want to try this on your old user or new user ? – Pankaj Yogi Aug 15 '17 at 9:11
  • 1
    Let us continue this discussion in chat. – Pankaj Yogi Aug 15 '17 at 9:16

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.