You are here

function userprotect_form_user_form_alter in User protect 8

Implements hook_form_FORM_ID_alter() for form "user_form".

File

./userprotect.module, line 209
Allows admins to protect users from being edited or cancelled.

Code

function userprotect_form_user_form_alter(&$form, &$form_state) {

  // Get account that is being edited.
  $build_info = $form_state
    ->getBuildInfo();
  $entity = $build_info['callback_object']
    ->getEntity();
  if ($entity
    ->isNew()) {

    // Don't protect fields when adding a new user.
    return;
  }

  // Get operating account.
  $account = \Drupal::currentUser();

  // Get available protection plugins.
  $manager = UserProtect::pluginManager();
  $protection_definitions = $manager
    ->getDefinitions();

  // For each protection plugin, check if the current user has access
  // to the element the plugin protects. If not, apply the protection.
  $applied = [];
  foreach ($protection_definitions as $protection_definition) {
    if (!$entity
      ->access($protection_definition['id'], $account)) {

      // Apply protection.
      $protection = $manager
        ->createInstance($protection_definition['id'], $protection_definition);
      $success = $protection
        ->applyAccountFormProtection($form, $form_state);
      if ($success) {
        $applied[$protection
          ->getPluginId()] = $protection
          ->label();
      }
    }
  }

  // Display a message about the applied protections if there were protections
  // applied and if the current user is an admin user.
  if (count($applied) && $account
    ->hasPermission('administer users')) {
    $message = t('%user has been protected from the following editing operations: @operations', [
      '%user' => $entity
        ->getAccountName(),
      '@operations' => implode(', ', $applied),
    ]);
    \Drupal::messenger()
      ->addMessage($message);
  }
}