You are here

public function UserPermissionsForm::submitForm in User Permissions 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 UserPermissionsForm::submitForm

File

src/Form/UserPermissionsForm.php, line 141

Class

UserPermissionsForm
User permissions form for granting permissions to individual users.

Namespace

Drupal\user_permissions\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $perms = [];
  $uid = (int) $form_state
    ->getValue('uid');
  $role_name = $form_state
    ->getValue('role_name');
  $input = $form_state
    ->getUserInput();
  if (array_key_exists($role_name, $input)) {
    $perms = $input[$role_name];
  }
  if ($role_name == USER_PERMISSIONS_NO_ROLE) {
    if (!empty($perms)) {

      // Creates a new role with the name $role_name.
      $role_name = '_user_role_' . $uid;
      $this->userRole = Role::create([
        'id' => $role_name,
        'label' => $role_name,
      ]);
      $this->userRole
        ->save();
      foreach ($form_state
        ->getValue('role_names') as $role_name => $name) {
        user_role_change_permissions($this->userRole
          ->label(), (array) $form_state
          ->getValue($role_name));
      }
    }

    // If $perms contains no permissions for the user, no role is created.
  }
  else {

    // Modifying existing user permissions.
    $perms_exist = array_filter($perms);
    if (empty($perms_exist)) {

      // If $perms has no permissions for the user,
      // this deletes all permission/role information related to this role.
      $this->userRole
        ->delete();
    }
    else {
      foreach ($form_state
        ->getValue('role_names') as $role_name => $name) {
        user_role_change_permissions($role_name, (array) $form_state
          ->getValue($role_name));
      }
    }
  }
}