You are here

public static function FileWidget::submit in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php \Drupal\file\Plugin\Field\FieldWidget\FileWidget::submit()

Form submission handler for upload/remove button of formElement().

This runs in addition to and after file_managed_file_submit().

See also

file_managed_file_submit()

File

core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php, line 524
Contains \Drupal\file\Plugin\Field\FieldWidget\FileWidget.

Class

FileWidget
Plugin implementation of the 'file_generic' widget.

Namespace

Drupal\file\Plugin\Field\FieldWidget

Code

public static function submit($form, FormStateInterface $form_state) {

  // During the form rebuild, formElement() will create field item widget
  // elements using re-indexed deltas, so clear out FormState::$input to
  // avoid a mismatch between old and new deltas. The rebuilt elements will
  // have #default_value set appropriately for the current state of the field,
  // so nothing is lost in doing this.
  $button = $form_state
    ->getTriggeringElement();
  $parents = array_slice($button['#parents'], 0, -2);
  NestedArray::setValue($form_state
    ->getUserInput(), $parents, NULL);

  // Go one level up in the form, to the widgets container.
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $parents = $element['#field_parents'];
  $submitted_values = NestedArray::getValue($form_state
    ->getValues(), array_slice($button['#parents'], 0, -2));
  foreach ($submitted_values as $delta => $submitted_value) {
    if (empty($submitted_value['fids'])) {
      unset($submitted_values[$delta]);
    }
  }

  // If there are more files uploaded via the same widget, we have to separate
  // them, as we display each file in it's own widget.
  $new_values = array();
  foreach ($submitted_values as $delta => $submitted_value) {
    if (is_array($submitted_value['fids'])) {
      foreach ($submitted_value['fids'] as $fid) {
        $new_value = $submitted_value;
        $new_value['fids'] = array(
          $fid,
        );
        $new_values[] = $new_value;
      }
    }
    else {
      $new_value = $submitted_value;
    }
  }

  // Re-index deltas after removing empty items.
  $submitted_values = array_values($new_values);

  // Update form_state values.
  NestedArray::setValue($form_state
    ->getValues(), array_slice($button['#parents'], 0, -2), $submitted_values);

  // Update items.
  $field_state = static::getWidgetState($parents, $field_name, $form_state);
  $field_state['items'] = $submitted_values;
  static::setWidgetState($parents, $field_name, $form_state, $field_state);
}