3

i'm trying to create custom drupal 7 module , i'm using 'user_roles()' function to get all the roles in the system , and then i assign those roles to checkboxes API Form Control

  $form['roles_group'] = array(
  '#type' => 'checkboxes',
  '#options' => drupal_map_assoc(user_roles()),
  '#default_value' => isset($field['roles_group']) ? $field['roles_group'] : '',
  '#required' => TRUE
);

in the display mode i'm getting a list of checkboxes like this :

<input type="checkbox" id="edit-mtc-roles-utilisateur-anonyme" name="mtc_roles[utilisateur anonyme]" value="utilisateur anonyme" class="form-checkbox">

in the :

name="mtc_roles[utilisateur anonyme]"

the system automatically put the human readable name in the 'Name' attribute of the inputs

and that's makes me wonder if there is a drupal 7 function that can assign a role by the 'human readable name' to a specific user , or do i have to fix attr '#options' in the form checkbox API

PS : the same issue with the content types

thanks in advance ^^

2
  • It is not clear what you mean by 'the same issue with the content types' but it is probably best to post a different question outlining the problem, rather than trying to get two solutions with one question.
    – Triskelion
    Commented Jun 3, 2013 at 21:32
  • @Triskelion 'the same issue with the content types' means when i try to get all the content type and add them in checkboxes list , i'm getting the same problem with the 'name' attr Commented Jun 3, 2013 at 22:10

1 Answer 1

4

Actually you do not assign the user to a role, but the reverse. You assign the role to the user.

First use the following to load the role using the plain langauge role name:

$new_role = user_role_load_by_name($role_name);

This loads the role object.

Then load the specific user using their user id:

$account = user_load($uid);

Then update the roles as follows:

$account->roles[$new_role->rid] = $new_role->name;

And save the user:

user_save($account);

This will add the role to the specified user.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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