You are here

function permissions_by_term_form_user_form_alter in Permissions by Term 8.2

Implements hook_form_FORM_ID_alter() for 'user_form'.

File

./permissions_by_term.module, line 234
Allows access to terms in a vocabulary to be limited by user or role.

Code

function permissions_by_term_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Nothing to do if the current user does not have requested permission.
  if (!\Drupal::currentUser()
    ->hasPermission('show term permissions on user edit page')) {
    return;
  }
  $form['access'] = [
    '#type' => 'details',
    '#title' => t('Permissions'),
    '#description' => t('Extend content access by giving access to the related taxonomy terms.'),
    '#open' => TRUE,
    '#weight' => -10,
  ];
  $term_storage = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term');
  $settings = \Drupal::config('permissions_by_term.settings');
  $target_bundles = $settings
    ->get('target_bundles');
  $terms = $target_bundles ? $term_storage
    ->loadByProperties([
    'vid' => $target_bundles,
  ]) : $term_storage
    ->loadMultiple();
  $form['access']['terms'] = [
    '#type' => 'select',
    '#multiple' => TRUE,
    '#options' => array_map(function (TermInterface $term) {
      return $term
        ->label();
    }, $terms),
    '#title' => t('Allowed terms'),
    '#description' => t('Choose a list of taxonomy terms. The access to the content, related to chosen taxonomy terms will be granted to this user.'),
  ];

  /** @var \Drupal\permissions_by_term\Service\AccessStorage $access_storage */
  $access_storage = \Drupal::service('permissions_by_term.access_storage');

  /** @var \Drupal\user\UserInterface $user */
  $user = $form_state
    ->getFormObject()
    ->getEntity();
  if (!$user
    ->isNew() && ($permitted_tids = $access_storage
    ->getPermittedTids($user
    ->id(), $user
    ->getRoles()))) {
    $form['access']['terms']['#default_value'] = array_values($permitted_tids);
  }
  $form['actions']['submit']['#submit'][] = 'permissions_by_term_user_form_submit';
}