function RoleForm::save

Same name and namespace in other branches
  1. 11.x core/modules/user/src/RoleForm.php \Drupal\user\RoleForm::save()
  2. 10 core/modules/user/src/RoleForm.php \Drupal\user\RoleForm::save()
  3. 9 core/modules/user/src/RoleForm.php \Drupal\user\RoleForm::save()
  4. 8.9.x core/modules/user/src/RoleForm.php \Drupal\user\RoleForm::save()

Overrides EntityForm::save

File

core/modules/user/src/RoleForm.php, line 52

Class

RoleForm
Form controller for the role entity edit forms.

Namespace

Drupal\user

Code

public function save(array $form, FormStateInterface $form_state) {
  $entity = $this->entity;
  // Prevent leading and trailing spaces in role names.
  $entity->set('label', trim($entity->label()));
  $status = $entity->save();
  // Create actions but ignore the authenticated and anonymous roles.
  if (!in_array($entity->id(), [
    RoleInterface::AUTHENTICATED_ID,
    RoleInterface::ANONYMOUS_ID,
  ])) {
    $type_manager = $this->entityTypeManager
      ->getStorage('action');
    $add_id = 'user_add_role_action.' . $entity->id();
    if (!$type_manager->load($add_id)) {
      $action = $type_manager->create([
        'id' => $add_id,
        'type' => 'user',
        'label' => $this->t('Add the @label role to the selected users', [
          '@label' => $entity->label(),
        ]),
        'configuration' => [
          'rid' => $entity->id(),
        ],
        'plugin' => 'user_add_role_action',
      ]);
      $action->save();
    }
    $remove_id = 'user_remove_role_action.' . $entity->id();
    if (!$type_manager->load($remove_id)) {
      $action = $type_manager->create([
        'id' => $remove_id,
        'type' => 'user',
        'label' => $this->t('Remove the @label role from the selected users', [
          '@label' => $entity->label(),
        ]),
        'configuration' => [
          'rid' => $entity->id(),
        ],
        'plugin' => 'user_remove_role_action',
      ]);
      $action->save();
    }
  }
  $edit_link = $this->entity
    ->toLink($this->t('Edit'), 'edit-form')
    ->toString();
  if ($status == SAVED_UPDATED) {
    $this->messenger()
      ->addStatus($this->t('Role %label has been updated.', [
      '%label' => $entity->label(),
    ]));
    $this->logger('user')
      ->info('Role %label has been updated.', [
      '%label' => $entity->label(),
      'link' => $edit_link,
    ]);
  }
  else {
    $this->messenger()
      ->addStatus($this->t('Role %label has been added.', [
      '%label' => $entity->label(),
    ]));
    $this->logger('user')
      ->info('Role %label has been added.', [
      '%label' => $entity->label(),
      'link' => $edit_link,
    ]);
  }
  $form_state->setRedirect('entity.user_role.collection');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.