Search code examples
drupaldrupal-7roles

Drupal: assign roles in user_save


I can't find a solution or right example for something that should be quite simple: assign a role to an user when creating it, this is what I'm trying:

$edit = array(
        'name' => $_POST['name'],
        'pass' => $password,
        'mail' => $_POST['email'],
        'status' => 0,
        'language' => 'es',
        'init' => $_POST['email'],
        array(2 =>'authenticated', 4=>'my custom role') //as id and named in role db table
      );

user_save(NULL, $edit);

The user is not being created, how can I do this?

Thank you


Solution

  • You haven't named the roles member as such. Try his modified version:

    $edit = array(
      'name' => $_POST['name'],
      'pass' => $password,
      'mail' => $_POST['email'],
      'status' => 0,
      'language' => 'es',
      'init' => $_POST['email'],
      'roles' => array(
        2 => 'authenticated',
        4 => 'my custom role',
      ),
    );
    
    user_save(NULL, $edit);