You are here

public function UserCsvImportForm::validateForm in User CSV import 8

Same name and namespace in other branches
  1. 2.0.x src/Form/UserCsvImportForm.php \Drupal\user_csv_import\Form\UserCsvImportForm::validateForm()
  2. 1.0.x src/Form/UserCsvImportForm.php \Drupal\user_csv_import\Form\UserCsvImportForm::validateForm()

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/UserCsvImportForm.php, line 181

Class

UserCsvImportForm
Provides methods to define and build the user import form.

Namespace

Drupal\user_csv_import\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {

  // Get form data.
  $roles = $form_state
    ->getValue([
    'config_options',
    'roles',
  ]);
  $fields = $form_state
    ->getValue([
    'config_fields',
    'fields',
  ]);

  // Filter vales and clean empty.
  $roles_selected = array_filter($roles, function ($item) {
    return $item;
  });
  $fields_selected = array_filter($fields, function ($item) {
    return $item;
  });

  // If there is no options selected, show the error.
  if (empty($roles_selected)) {
    $form_state
      ->setErrorByName('roles', $this
      ->t('Please select at least one role to apply to the imported user(s).'));
  }
  elseif (empty($fields_selected)) {
    $form_state
      ->setErrorByName('fields', $this
      ->t('Please select at least one field to apply to the imported user(s).'));

    // If "mail" and "name" fields are not selected, show an error.
  }
  elseif (!array_key_exists('mail', $fields_selected) or !array_key_exists('name', $fields_selected)) {
    $form_state
      ->setErrorByName('roles', $this
      ->t('The email and username fields is required'));
  }

  // Validate file.
  $this->file = file_save_upload('file', $form['file']['#upload_validators']);
  if (!$this->file[0]) {
    $form_state
      ->setErrorByName('file');
  }
}