Hi everyone, I'm currently using the following code to assign roles to "paid" users in a function. The users are automatically assigned "unpaid" role, rid=7, on registration. I want to change it to "paid", rid=6, in this function.

The following bit of code successfully does this.

the variable $uid is available

$result = db_query("DELETE FROM {users_roles} WHERE uid=%d AND rid=7", $uid, $rid);
      if ($result)
      {
      watchdog('fee', "Removed 'Unpaid' role from user $name (User $uid, $mail)");
      }
      else
      {
      watchdog('fee', "Failed to remove 'Unpaid' role from $name (User $uid, $mail)");
      }

$result = db_query("INSERT INTO {users_roles} (uid, rid) values (%d, 6)", $uid, $rid);
cache_clear_all($uid .':', 'cache_menu', TRUE);
      if ($result)
      {
drupal_set_message("You have been successfully marked as paid.");
      watchdog('fee', "Added 'Paid' role to user $name (User $uid, $mail)");
      }
      else
      {
      drupal_set_message("We have failed to verify your payment. Please email us.");
      watchdog('fee', "Failed to add 'Paid' role to $name (User $uid, $mail)");
      }

However, I want to use the function user_save to do this to maintain compatibility across other modules.
Please can someone help me

Comments

marcvangend’s picture

The API docs should answer your question: http://api.drupal.org/api/function/user_save/5.

$account The $user object for the user to modify or add. If $user->uid is omitted, a new user will be added.
$array An array of fields and values to save. For example array('name' => 'My name'); Setting a field to NULL deletes it from the data column.

iamwhoiam’s picture

Unfortunately I think the role field is a little bit more complicated...

My 'unpaid' role has rid=7, my paid role has rid=6

I'm up to the following code:

$new_roles = array('6' => 'paid');
user_save($uid, array('roles' => $new_roles));

But that only adds rid=6 to the user_roles table

rid 3,4,5 and 7 are deleted due:

    if (is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);

within user_save

marcp’s picture

Take a look at userplus to see how it's done there.