You are here

public function GroupMembership::changeRoles in Group 7

Change roles for a membership.

This function may be used to grant and revoke multiple roles at once. For example, when a form exposes checkboxes to configure roles for a membership, the form submit handler may directly pass the submitted values for the checkboxes form element to this function.

This is merely a helper function that sets the 'roles' property and then saves the GroupMembership. The actual business logic can be found in GroupMembershipController::save().

array(
  'group_admin' => 0,
  // Revoke 'group_admin'
  'group_admin' => FALSE,
  // Revoke 'group_admin'
  'sub_admin' => 1,
  // Grant 'sub_admin'
  'sub_admin' => TRUE,
  // Grant 'sub_admin'
  'sub_admin' => 'sub_admin',
);

Parameters

$roles: An associative array, where the key holds the role name and the value determines whether to grant or revoke that role. Any value that evaluates to TRUE will cause the role to be granted. Any value that evaluates to FALSE will cause the role to be revoked. Existing roles are not changed, unless specified in $roles.

See also

GroupMembershipController::save()

File

classes/group_membership.inc, line 104
Defines the Entity API class for group memberships.

Class

GroupMembership
Main class for group memberships.

Code

public function changeRoles(array $roles) {

  // Find out what roles we want to grant or revoke.
  $grant = array_filter($roles);
  $revoke = array_diff_assoc($roles, $grant);

  // Grant new roles for the membership.
  $this->roles = array_merge($this->roles, array_keys($grant));

  // Revoke roles from the membership.
  $this->roles = array_diff($this->roles, array_keys($revoke));

  // Save the membership so the roles are actually updated.
  $this
    ->save();
}