function role_delegation_field_widget_form_alter in Role Delegation 8
Implements hook_field_widget_form_alter().
File
- ./
role_delegation.module, line 127 - Allows admins to grant roles the authority to assign selected roles to users.
Code
function role_delegation_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
$items = $context['items'];
$field_definition = $items
->getFieldDefinition();
// Since the field is computed, the default value of the form element will be
// empty, so we need to adjust it.
if ($field_definition
->getTargetEntityTypeId() === 'user' && $field_definition
->getName() === 'role_change' && isset($element['#options'])) {
$roles_current = $items
->getEntity()
->getRoles();
$roles_options = array_keys($element['#options']);
$element['#default_value'] = array_intersect($roles_current, $roles_options);
}
}