You are here

public static function ImageWidget::value in PlUPload File Widget 8

Important!! The core FILE API relies on the value callback to save the managed file, not the submit handler. The submit handler is only used for file deletions.

Overrides FileWidget::value

File

src/Plugin/Field/FieldWidget/ImageWidget.php, line 130

Class

ImageWidget
Plugin annotation @FieldWidget( id = "plupload_image_widget", label = @Translation("PLupload widget"), field_types = { "image" } )

Namespace

Drupal\plupload_widget\Plugin\Field\FieldWidget

Code

public static function value($element, $input = FALSE, FormStateInterface $form_state) {

  // We need to fake the element ID for the PlUploadFile form element
  // to work as expected as it is being nested in a form sub-element calle
  // upload.
  $id = $element['#id'];
  $id_backup = $id;

  // If a unique identifier added with '--', we need to exclude it
  if (preg_match('/(.*)(--[0-9A-Za-z-]+)$/', $id, $reg)) {
    $id = $reg[1];
  }

  // The form element is going to tell us if one
  // or more files where uploaded.
  $element['#id'] = $id . '-upload';
  $files = \Drupal\plupload\Element\PlUploadFile::valueCallback($element, $input, $form_state);
  $element['#id'] = $id_backup;
  if (empty($files)) {
    return parent::value($element, $input, $form_state);
  }

  // During form rebuild after submit or ajax request this
  // method might be called twice, but we do not want to
  // generate the file entities twice....
  // This files are RAW files, they are not registered
  // anywhere, so won't get deleted on CRON runs :(
  $file = reset($files);
  $destination = \Drupal::config('system.file')
    ->get('default_scheme') . '://' . $file['name'];
  $destination = file_stream_wrapper_uri_normalize($destination);

  /** @var \Drupal\file\Entity\File */
  $f = entity_create('file', array(
    'uri' => $file['tmppath'],
    'uid' => \Drupal::currentUser()
      ->id(),
    'status' => 0,
    'filename' => drupal_basename($destination),
    'filemime' => \Drupal::service('file.mime_type.guesser')
      ->guess($destination),
  ));
  $f
    ->save();
  $return['fids'][] = $f
    ->id();
  return $return;
}