1

I'm trying to grant a specific role to users that order an amount equal or greater than 100.00 €: Conditional Actions is going really near the achievement, but I'm failing on the action (PHP required).

How can I grant a role using a PHP action in Ubercart Conditional Actions?

apaderno
  • 28,547
  • 16
  • 75
  • 90
dag729
  • 199
  • 4
  • 10
  • possible duplicate of [How to assign role with PHP in Drupal?](http://stackoverflow.com/questions/3533415/how-to-assign-role-with-php-in-drupal) – apaderno Aug 24 '10 at 05:22
  • Yes, you're right, I can't remember why I submitted the same question twice on the same day...the other one has received more attention though. – dag729 Aug 24 '10 at 19:53

2 Answers2

3

Based on a couple of related threads, I think you want to add an "Execute custom PHP code" action along the lines of the following (substituting in the appropriate role name in line #3):

if($account) {
  $uid = $account->uid;
  $role_name = 'YOUR SPECIFIC ROLE NAME GOES HERE';
  $rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role_name));

  // Load user object
  $account = user_load(array('uid' => 1));

  // Save the user object with the new roles.
  if ($account !== FALSE) {
    $roles = $account->roles + array($rid => $role_name);
    user_save($account, array('roles' => $roles));

  watchdog('user', 'uc ca added role to Ubercart created user');
Community
  • 1
  • 1
Matt V.
  • 9,703
  • 10
  • 35
  • 56
  • I would rather suggest the usage of the core `user_multiple_role_edit()` function: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_multiple_role_edit/6, where the `$accounts` has to be an array of uids, the `$operation` has to be equal to `"add_role"`, and the `$rid` has to be equal to the id of the given role (which you can discover with a search of the return value of `user_roles()`: http://api.drupal.org/api/drupal/modules!user!user.module/function/user_roles/6). It's very easy to use. – Sk8erPeter Mar 05 '12 at 21:17
3

Code provided needs to close two brackets. I dropped the if statements, grabbed the uid from the order and fixed the uid setting (it was '1'):

  $uid = $order->uid;
  $role_name = 'customer';
  $rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role_name));

  // Load user object
  $account = user_load(array('uid' => $uid));

  // Save the user object with the new roles.
  $roles = $account->roles + array($rid => $role_name);
  user_save($account, array('roles' => $roles));

  watchdog('user', 'uc ca added role to Ubercart created user');
Bitmap
  • 12,402
  • 16
  • 64
  • 91
gjmokcb
  • 31
  • 1