You are here

public static function Upload::valueCallback in Lightning Media 8.2

Same name and namespace in other branches
  1. 8.4 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()
  2. 8 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()
  3. 8.3 src/Element/Upload.php \Drupal\lightning_media\Element\Upload::valueCallback()

Determines how user input is mapped to an element's #value property.

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 FormElement::valueCallback

File

src/Element/Upload.php, line 85

Class

Upload
A form element to handle file uploads.

Namespace

Drupal\lightning_media\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  $id = implode('_', $element['#parents']);
  $upload = \Drupal::request()->files
    ->get($id);
  if ($upload instanceof UploadedFile) {
    $destination = \Drupal::service('file_system')
      ->realPath($element['#upload_location']);
    $name = file_munge_filename($upload
      ->getClientOriginalName(), NULL);
    $name = file_create_filename($name, $destination);
    $name = $upload
      ->move($destination, $name)
      ->getFilename();
    $uri = $element['#upload_location'];
    if (substr($uri, -1) != '/') {
      $uri .= '/';
    }
    $uri .= $name;
    $file = File::create([
      'uri' => $uri,
      'uid' => \Drupal::currentUser()
        ->id(),
    ]);
    $file
      ->setTemporary();
    $file
      ->save();
    \Drupal::request()->files
      ->remove($id);
    return $file
      ->id();
  }
  else {
    return NULL;
  }
}