You are here

public static function CpfWidgetBase::validateElement in CPF 8

Form element validation handler for the 'cpf' element.

Checks that, in a field with multiple entries, the same CPF numbers have been entered.

File

src/CpfWidgetBase.php, line 46

Class

CpfWidgetBase
Base class for 'Field widget' plugin implementations.

Namespace

Drupal\cpf

Code

public static function validateElement($element, FormStateInterface $form_state, $form) {
  $widget = $element['#element_validate'][0][0];
  $element_value = $element['#value'];
  if (empty($element_value)) {
    return;
  }
  $field_name = $element['#field_name'];
  $user_input = $form_state
    ->getUserInput();
  $field_values = $user_input[$field_name];
  $field_values = array_filter(array_column($field_values, 'value'));
  $field_values = array_count_values($field_values);
  if ($field_values[$element_value] > 1) {
    $form_state
      ->setError($element, $widget
      ->t('You cannot enter the same CPF numbers.'));
    return;
  }
}