You are here

function filefield_sources_element_validate in FileField Sources 8

Same name and namespace in other branches
  1. 6 filefield_sources.module \filefield_sources_element_validate()
  2. 7 filefield_sources.module \filefield_sources_element_validate()

Validate a file based on the $element['#upload_validators'] property.

2 calls to filefield_sources_element_validate()
Imce::value in src/Plugin/FilefieldSource/Imce.php
Value callback for file field source plugin.
Reference::value in src/Plugin/FilefieldSource/Reference.php
Value callback for file field source plugin.

File

./filefield_sources.module, line 625
Extend FileField to allow files from multiple sources.

Code

function filefield_sources_element_validate($element, $file, FormStateInterface $form_state) {
  $validators = $element['#upload_validators'];
  $errors = [];

  // Since this frequently is used to reference existing files, check that
  // they exist first in addition to the normal validations.
  if (!file_exists($file
    ->getFileUri())) {
    $errors[] = t('The file does not exist.');
  }
  else {
    foreach ($validators as $function => $args) {

      // Add the $file variable to the list of arguments and pass it by
      // reference (required for PHP 5.3 and higher).
      array_unshift($args, NULL);
      $args[0] =& $file;
      $errors = array_merge($errors, call_user_func_array($function, $args));
    }
  }

  // Check for validation errors.
  if (!empty($errors)) {
    $message = t('The selected file %name could not be referenced.', [
      '%name' => $file->filename,
    ]);
    if (count($errors) > 1) {
      $message .= '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
    }
    else {
      $message .= ' ' . array_pop($errors);
    }
    $form_state
      ->setError($element, $message);
    return 0;
  }
  return 1;
}