You are here

function unique_field_user_form_validate in Unique field 8.2

Validate the user fields for unique field conditions on submission.

1 string reference to 'unique_field_user_form_validate'
unique_field_form_alter in ./unique_field.module
Hook_form_BASE_FORM_ID_alter().

File

./unique_field.module, line 442

Code

function unique_field_user_form_validate(array &$form, FormStateInterface $form_state) {

  // If override permission set show warring message and skip validation.
  if ($form_state
    ->getValues()['unique_field_override'] == 1) {
    return;
  }

  // Load default  configuration for validation.
  $config = \Drupal::configFactory()
    ->get('unique_field.settings');
  $fields = $config
    ->get('unique_field_user.fields');
  $comp_type = $config
    ->get('unique_field_user.comp');
  if ($comp_type == UNIQUE_FIELD_COMP_ALL) {
    $query = db_select('users_field_data', 'u');
    $query
      ->fields('n', array(
      'nid',
    ));
  }
  foreach ($fields as $field_name) {
    if ($comp_type == UNIQUE_FIELD_COMP_EACH) {
      $query = db_select('users_field_data', 'u');
      $query
        ->fields('u', array(
        'uid',
      ));
    }
    $query = db_select('users_field_data', 'u');
    $query
      ->fields('u', array(
      'uid',
    ));
    $field_type = \Drupal\field\Entity\FieldStorageConfig::loadByName('user', $field_name)
      ->get('type');
    $values = $form_state
      ->getValues()[$field_name];
    $field_values = array();
    foreach ($values as $value) {
      $field_values[] = $field_type == 'entity_reference' ? $value['target_id'] : $value['value'];
    }
    $table_name = 'user__' . $field_name;
    $col_name = $field_type == 'entity_reference' ? $field_name . '_target_id' : $field_name . '_value';
    $query
      ->join($table_name, 'f', 'u.uid = f.entity_id');
    $query
      ->condition('f.' . $col_name, $field_values, 'IN');
    $res = $query
      ->execute()
      ->fetchField();
    if ($res) {
      $form_state
        ->setErrorByName($field_name, t('The field @field_name has to be unique.', array(
        '@field_name' => $field_name,
      )));
      $user = \Drupal::currentUser();
      if ($user
        ->hasPermission('unique_field_perm_bypass')) {
        $form_id = str_replace('_', '-', $form['#id']);
        $msg = t('Your form has unique field validation errors. Click !here to bypass this check and resubmit.', array(
          '!here' => "<a href=\"#\" onclick=\"jQuery('form#" . $form_id . " input[name=\\'unique_field_override\\']').val(1);jQuery('form#" . $form_id . "').submit();return false;\">" . t('here') . '</a>',
        ));
        drupal_set_message($msg, 'warning');
      }
      $form_state
        ->setRebuild();
    }
  }
}