You are here

public static function Attach::filePathValidate in FileField Sources 8

Validate file path.

Parameters

array $element: Form element.

\Drupal\Core\Form\FormStateInterface $form_state: Form state.

array $complete_form: Complete form.

File

src/Plugin/FilefieldSource/Attach.php, line 328

Class

Attach
A FileField source plugin to allow use of files within a server directory.

Namespace

Drupal\filefield_sources\Plugin\FilefieldSource

Code

public static function filePathValidate(array &$element, FormStateInterface $form_state, array &$complete_form) {
  $parents = $element['#parents'];
  array_pop($parents);
  $input_exists = FALSE;

  // Get input of the whole parent element.
  $input = NestedArray::getValue($form_state
    ->getValues(), $parents, $input_exists);
  if ($input_exists) {

    // Only validate if this source is enabled.
    if (!$input['sources']['attach']) {
      return;
    }

    // Strip slashes from the end of the file path.
    $filepath = rtrim($element['path']['#value'], '\\/');
    $form_state
      ->setValueForElement($element['path'], $filepath);
    $filepath = static::getDirectory($input['source_attach']);

    // Check that the directory exists and is writable.
    if (!\Drupal::service('file_system')
      ->prepareDirectory($filepath, FileSystemInterface::CREATE_DIRECTORY)) {
      $form_state
        ->setError($element['path'], t('Specified file attach path %path must exist or be writable.', [
        '%path' => $filepath,
      ]));
    }
  }
}