I am writing a module called "Applicant" and I want it to add a role called "applicant" to a user after the user creates their own account.


name = Applicant
description = Handles Applicant User Actions
core = 7.x


function applicant_user_insert(){


What would I include inside of the hook in applicant.module to access the current user's roles and add "Applicant"?


see api page for reference. Replace the values for your "Applicant" role:

 * Implements hook_user_insert().
function applicant_user_insert(&$edit, $account, $category) {
  // id of role (probably not neccessary, added here to avoid multiple assertions)
  $key = 3;
  // role's machine name
  $role = 'administrator';
  $account->roles[$key] = $role;
  • why is $key set to 3? Can we access the current key of the user without setting it statically? – Emanegux Mar 18 '14 at 19:33
  • $key is not the user id, it is the role id. see {role} table in your database for reference – Andre Baumeier Mar 18 '14 at 19:34
  • you probably could do $account->roles[] = 'newrole'; as well, but that could cause ->roles to contain multiple times 'newrole' and I am not sure how drupal would react to that, so either add the id, or use in_array(). – Andre Baumeier Mar 18 '14 at 19:35
  • +1 for working code but doesn't using the raw ID work against modular implementation? – Emanegux Mar 18 '14 at 20:00
  • I think it would make the most sense to create the role in applicant.install file instead of relying on the CMS to tell you if the roll you describe is the roll you want. Thank you for the answer. – Emanegux Mar 18 '14 at 20:09

Don't re-invent the wheel! https://drupal.org/project/registration_role

Also I think you want to look at user_presave, rather than user_insert. https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7

  • hook_user_presave is also called on account edit. – Andre Baumeier Mar 18 '14 at 19:28
  • but what if 4 lines of code all I want? – Emanegux Mar 18 '14 at 19:28
  • 1
    if you strip out the comments and unnecessary variables - my answer has 3 lines only ;) – Andre Baumeier Mar 18 '14 at 19:31

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.