You are here

function permissions_by_term_validate in Permissions by Term 8

Same name and namespace in other branches
  1. 8.2 permissions_by_term.module \permissions_by_term_validate()
  2. 7 permissions_by_term.module \permissions_by_term_validate()

Validation handler for permissions_by_term_form_alter().

2 string references to 'permissions_by_term_validate'
permissions_by_term_form_alter in ./permissions_by_term.module
Implements hook_form_alter().
permissions_by_term_form_taxonomy_term_form_alter in ./permissions_by_term.module
Implements hook_form_alter().

File

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

Code

function permissions_by_term_validate($form, FormState $oFormState) {
  foreach ($form as $field) {
    if (!is_object($field) && !empty($field['widget']['target_id']['#target_type']) && $field['widget']['target_id']['#target_type'] == 'taxonomy_term') {
      $field_name = $field['widget']['#field_name'];
      $terms = $oFormState
        ->getValues()[$field_name]['target_id'];
      $not_allowed_term_names = [];
      if (!empty($terms)) {
        foreach ($terms as $term) {
          if (!empty($term['target_id'])) {
            $term_id = $term['target_id'];

            /* @var \Drupal\permissions_by_term\Service\AccessCheck $access_check_service */
            $access_check_service = \Drupal::service('permissions_by_term.access_check');
            if (!$access_check_service
              ->isAccessAllowedByDatabase($term_id)) {
              $term = Term::load($term_id);
              $not_allowed_term_names[] = $term
                ->getName();
            }
          }
        }
      }
    }
  }
  if (!empty($not_allowed_term_names)) {
    if (count($not_allowed_term_names) > 1) {
      $term_names = implode(', ', $not_allowed_term_names);
    }
    else {
      $term_names = $not_allowed_term_names['0'];
    }
    $oFormState
      ->setErrorByName('field_tags', t('You are not allowed to use taxonomy terms like: "@termNames". Remove the restricted taxonomy terms from the form field and try again.', [
      '@termNames' => $term_names,
    ]));
  }
}