How to assign role with PHP in Drupal?

前端 未结 4 2074
误落风尘
误落风尘 2021-02-06 16:38

I need to assign a kind of \"premium status\" to members that purchase an amount equal or greater than 100 € via PHP.

Conditional Actions are already set up (user = anon

4条回答
  •  忘了有多久
    2021-02-06 17:00

    You can do this with user_load() and user_save():

    $uid = 1; // UID of user to add role to
    $role_name = 'test role'; // Name of role to add
    
    // Get RID of role
    $rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
    
    // Load user object
    $account = user_load(array('uid' => 1));
    
    // Save the user object with the new roles.
    if ($account !== FALSE && !isset($account->roles[$rid])) {
      $roles = $account->roles + array($rid => $role_name);
      user_save($account, array('roles' => $roles));
    }
    

    If you wanted to do this in bulk for multiple users, there's user_multiple_role_edit():

    $uids = array(1, 2, 3, 4); // UIDs of users to add role to
    $role_name = 'test role'; // Name of role to add
    
    // Get RID of role
    $rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
    
    // Add the role to UIDs
    user_multiple_role_edit($uids, 'add_role', $rid);
    

    Edit

    If you wanted to do this for the current user (like part of the check you mentioned in a comment), you can do:

    // Check for value over 100.00
    if ($total_value > 100) {
      global $user; // Retrieve user object for currently logged in user.
    
      $role_name = 'test role'; // Name of role to add
    
      // Get RID of role
      $rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
    
      // Save the user object with the new role.
      if (!isset($user->roles[$rid])) {
        $roles = $user->roles + array($rid => $role_name);
        user_save($user, array('roles' => $roles));
      }
    }
    // Other code here.
    

提交回复
热议问题