rockstardev
rockstardev

Reputation: 13527

Adding a rule that checks if the user's role has changed?

Is there a way to add a rule that can do a certain action when a user's role is changed?

Upvotes: 1

Views: 1242

Answers (3)

Citricguy
Citricguy

Reputation: 421

Simply create a "Use PHP code" condition and fire on the "An existing user account has been updated" Rules hook and enter the following snippet of PHP code:

return (count(array_diff_key($account->roles, $account_unchanged->roles)) + count(array_diff_key($account_unchanged->roles, $account->roles))) <> 0;

This will catch both the additions and removals from any roles and return true when roles have been modified.

Upvotes: 0

doub1ejack
doub1ejack

Reputation: 11171

I know this is coming 5 years too late, but I just had to solve this problem so I though I'd share. The Rules module can totally do this, but it took me a little while to work it out:

Add a condition for the rule you are transitioning from:

  1. Create a new rule and for "React on Event" select "Before Saving a User Account"
  2. Add a new condition and for "Select the Condition to Add" select "Data > List Contains Item"
  3. Under the "Data Selectors" you will see "account-unchanged:roles". Paste that into the Data Selector field.
  4. If you see another Data Selector for the "Item", click the "Switch to the Direct Input Mode" button
  5. Pick the combination of roles you expect the user to have before the change in roles.

Then add a condition for the rule you are transitioning to. This is the same as above except for steps 3 & 5:

  • 3 - Instead of "account-unchanged:roles" pick "account:roles"
  • 5 - Pick the combination of roles you expect the user to have after the change in roles.

Upvotes: 1

Henrik Opel
Henrik Opel

Reputation: 19441

I do not know if the trigger/action modules or some extension modules for these offer this (might be worth a check), but if not, you'd probably need to implement hook_user() for the 'update' operation.

There you'd need to compare the $edit values against the $account values to check for a change of role(s). Be aware that at this point the change is not yet 'commited', so the update could still fail. Depending on what you want to do on a role change, you might need to put some marker in the $edit array so that you can react to a successful submission later on (e.g. in the after_update operation).

Upvotes: 0

Related Questions