You are here

public static function Reference::value in FileField Sources 8

Value callback for file field source plugin.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

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

Return value

mixed The value to assign to the element.

Overrides FilefieldSourceInterface::value

File

src/Plugin/FilefieldSource/Reference.php, line 31

Class

Reference
A FileField source plugin to allow referencing of existing files.

Namespace

Drupal\filefield_sources\Plugin\FilefieldSource

Code

public static function value(array &$element, &$input, FormStateInterface $form_state) {
  if (isset($input['filefield_reference']['autocomplete']) && strlen($input['filefield_reference']['autocomplete']) > 0 && $input['filefield_reference']['autocomplete'] != FILEFIELD_SOURCE_REFERENCE_HINT_TEXT) {
    $matches = [];
    if (preg_match('/\\[fid:(\\d+)\\]/', $input['filefield_reference']['autocomplete'], $matches)) {
      $fid = $matches[1];
      if ($file = File::load($fid)) {

        // Remove file size restrictions, since the file already exists on
        // disk.
        if (isset($element['#upload_validators']['file_validate_size'])) {
          unset($element['#upload_validators']['file_validate_size']);
        }

        // Check that the user has access to this file through
        // hook_download().
        if (!$file
          ->access('download')) {
          $form_state
            ->setError($element, t('You do not have permission to use the selected file.'));
        }
        elseif (filefield_sources_element_validate($element, (object) $file, $form_state)) {
          if (!in_array($file
            ->id(), $input['fids'])) {
            $input['fids'][] = $file
              ->id();
          }
        }
      }
      else {
        $form_state
          ->setError($element, t('The referenced file could not be used because the file does not exist in the database.'));
      }
    }

    // No matter what happens, clear the value from the autocomplete.
    $input['filefield_reference']['autocomplete'] = '';
  }
}