You are here

public function DuplicateRoleForm::submitForm in Duplicate role 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/DuplicateRoleForm.php, line 119

Class

DuplicateRoleForm
Provides a form for adding a new role.

Namespace

Drupal\duplicate_role\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $roles = user_role_names();
  $base_role_id = $this->routeMatch
    ->getParameter('role');
  if (!isset($roles[$base_role_id])) {
    $base_role_id = $form_state
      ->getValue('base_role');
  }
  $new_role_name = $form_state
    ->getValue('label');
  $new_role_id = $form_state
    ->getValue('id');

  /** @var \Drupal\user\RoleInterface $role */
  $base_role = $this->entityTypeManager
    ->getStorage('user_role')
    ->load($base_role_id);
  if ($base_role !== NULL) {
    $new_role = Role::create([
      'id' => $new_role_id,
      'label' => $new_role_name,
    ]);
    $new_role
      ->save();
    user_role_grant_permissions($new_role
      ->id(), $base_role
      ->getPermissions());
    $this->messenger
      ->addStatus($this
      ->t('Role %role_name has been added.', [
      '%role_name' => $new_role_name,
    ]));
    $form_state
      ->setRedirect('entity.user_role.collection');
  }
  else {
    $this->messenger
      ->addError($this
      ->t('Base role %base_role_id not found.', [
      '%base_role_id' => $base_role_id,
    ]));
  }
}