You are here

public static function FileWidget::processMultiple in Drupal 9

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

Form API callback: Processes a group of file_generic field elements.

Adds the weight field to each row so it can be ordered and adds a new Ajax wrapper around the entire group so it can be replaced all at once.

This method on is assigned as a #process callback in formMultipleElements() method.

File

core/modules/file/src/Plugin/Field/FieldWidget/FileWidget.php, line 459

Class

FileWidget
Plugin implementation of the 'file_generic' widget.

Namespace

Drupal\file\Plugin\Field\FieldWidget

Code

public static function processMultiple($element, FormStateInterface $form_state, $form) {
  $element_children = Element::children($element, TRUE);
  $count = count($element_children);

  // Count the number of already uploaded files, in order to display new
  // items in \Drupal\file\Element\ManagedFile::uploadAjaxCallback().
  if (!$form_state
    ->isRebuilding()) {
    $count_items_before = 0;
    foreach ($element_children as $children) {
      if (!empty($element[$children]['#default_value']['fids'])) {
        $count_items_before++;
      }
    }
    $form_state
      ->set('file_upload_delta_initial', $count_items_before);
  }
  foreach ($element_children as $delta => $key) {
    if ($key != $element['#file_upload_delta']) {
      $description = static::getDescriptionFromElement($element[$key]);
      $element[$key]['_weight'] = [
        '#type' => 'weight',
        '#title' => $description ? t('Weight for @title', [
          '@title' => $description,
        ]) : t('Weight for new file'),
        '#title_display' => 'invisible',
        '#delta' => $count,
        '#default_value' => $delta,
      ];
    }
    else {

      // The title needs to be assigned to the upload field so that validation
      // errors include the correct widget label.
      $element[$key]['#title'] = $element['#title'];
      $element[$key]['_weight'] = [
        '#type' => 'hidden',
        '#default_value' => $delta,
      ];
    }
  }

  // Add a new wrapper around all the elements for Ajax replacement.
  $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
  $element['#suffix'] = '</div>';
  return $element;
}