FileWidget.php 19.7 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\file\Plugin\Field\FieldWidget\FileWidget.
6 7
 */

8
namespace Drupal\file\Plugin\Field\FieldWidget;
9

10
use Drupal\Component\Utility\String;
11
use Drupal\Core\Field\FieldDefinitionInterface;
12
use Drupal\Core\Field\WidgetBase;
13
use Drupal\Core\Field\FieldItemListInterface;
14
use Drupal\Component\Utility\NestedArray;
15
use Drupal\Core\Render\Element;
16 17 18 19

/**
 * Plugin implementation of the 'file_generic' widget.
 *
20
 * @FieldWidget(
21 22 23 24
 *   id = "file_generic",
 *   label = @Translation("File"),
 *   field_types = {
 *     "file"
25
 *   }
26 27 28 29
 * )
 */
class FileWidget extends WidgetBase {

30 31 32 33 34 35 36 37 38
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'progress_indicator' => 'throbber',
    ) + parent::defaultSettings();
  }

39
  /**
40
   * {@inheritdoc}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
   */
  public function settingsForm(array $form, array &$form_state) {
    $element['progress_indicator'] = array(
      '#type' => 'radios',
      '#title' => t('Progress indicator'),
      '#options' => array(
        'throbber' => t('Throbber'),
        'bar' => t('Bar with progress meter'),
      ),
      '#default_value' => $this->getSetting('progress_indicator'),
      '#description' => t('The throbber display does not show the status of uploads but takes up less space. The progress bar is helpful for monitoring progress on large uploads.'),
      '#weight' => 16,
      '#access' => file_progress_implementation(),
    );
    return $element;
  }

  /**
59
   * {@inheritdoc}
60 61 62 63 64 65 66 67
   */
  public function settingsSummary() {
    $summary = array();
    $summary[] = t('Progress indicator: @progress_indicator', array('@progress_indicator' => $this->getSetting('progress_indicator')));
    return $summary;
  }

  /**
68
   * Overrides \Drupal\Core\Field\WidgetBase::formMultipleElements().
69 70 71
   *
   * Special handling for draggable multiple widgets and 'add more' button.
   */
72
  protected function formMultipleElements(FieldItemListInterface $items, array &$form, array &$form_state) {
73
    $field_name = $this->fieldDefinition->getName();
74 75 76 77 78
    $parents = $form['#parents'];

    // Load the items for form rebuilds from the field state as they might not be
    // in $form_state['values'] because of validation limitations. Also, they are
    // only passed in as $items when editing existing entities.
79
    $field_state = field_form_get_state($parents, $field_name, $form_state);
80
    if (isset($field_state['items'])) {
81
      $items->setValue($field_state['items']);
82 83 84
    }

    // Determine the number of widgets to display.
85
    $cardinality = $this->fieldDefinition->getCardinality();
86
    switch ($cardinality) {
87
      case FieldDefinitionInterface::CARDINALITY_UNLIMITED:
88 89 90 91 92
        $max = count($items);
        $is_multiple = TRUE;
        break;

      default:
93 94
        $max = $cardinality - 1;
        $is_multiple = ($cardinality > 1);
95 96 97
        break;
    }

98
    $title = String::checkPlain($this->fieldDefinition->getLabel());
99
    $description = field_filter_xss($this->fieldDefinition->getDescription());
100 101 102 103 104 105 106 107 108 109

    $elements = array();

    $delta = 0;
    // Add an element for every existing item.
    foreach ($items as $item) {
      $element = array(
        '#title' => $title,
        '#description' => $description,
      );
110
      $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
111 112 113 114 115 116 117 118 119 120 121 122

      if ($element) {
        // Input field for the delta (drag-n-drop reordering).
        if ($is_multiple) {
          // We name the element '_weight' to avoid clashing with elements
          // defined by widget.
          $element['_weight'] = array(
            '#type' => 'weight',
            '#title' => t('Weight for row @number', array('@number' => $delta + 1)),
            '#title_display' => 'invisible',
            // Note: this 'delta' is the FAPI #type 'weight' element's property.
            '#delta' => $max,
123
            '#default_value' => $item->_weight ?: $delta,
124 125 126 127 128 129 130 131 132
            '#weight' => 100,
          );
        }

        $elements[$delta] = $element;
        $delta++;
      }
    }

133
    $empty_single_allowed = ($cardinality == 1 && $delta == 0);
134
    $empty_multiple_allowed = ($cardinality == FieldDefinitionInterface::CARDINALITY_UNLIMITED || $delta < $cardinality) && empty($form_state['programmed']);
135 136 137 138 139 140 141 142

    // Add one more empty row for new uploads except when this is a programmed
    // multiple form as it is not necessary.
    if ($empty_single_allowed || $empty_multiple_allowed) {
      $element = array(
        '#title' => $title,
        '#description' => $description,
      );
143
      $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
144 145 146 147 148 149 150 151 152 153
      if ($element) {
        $element['#required'] = ($element['#required'] && $delta == 0);
        $elements[$delta] = $element;
      }
    }

    if ($is_multiple) {
      // The group of elements all-together need some extra functionality after
      // building up the full list (like draggable table rows).
      $elements['#file_upload_delta'] = $delta;
154
      $elements['#type'] = 'details';
155
      $elements['#open'] = TRUE;
156
      $elements['#theme'] = 'file_widget_multiple';
157
      $elements['#theme_wrappers'] = array('details');
158
      $elements['#process'] = array(array(get_class($this), 'processMultiple'));
159 160 161 162 163
      $elements['#title'] = $title;

      $elements['#description'] = $description;
      $elements['#field_name'] = $element['#field_name'];
      $elements['#language'] = $element['#language'];
164
      $elements['#display_field'] = (bool) $this->getFieldSetting('display_field');
165 166 167 168 169
      // The field settings include defaults for the field type. However, this
      // widget is a base class for other widgets (e.g., ImageWidget) that may
      // act on field types without these expected settings.
      $field_settings = $this->getFieldSettings() + array('display_field' => NULL);
      $elements['#display_field'] = (bool) $field_settings['display_field'];
170 171 172 173 174

      // Add some properties that will eventually be added to the file upload
      // field. These are added here so that they may be referenced easily
      // through a hook_form_alter().
      $elements['#file_upload_title'] = t('Add a new file');
175 176 177 178 179 180
      $elements['#file_upload_description'] = array(
        '#theme' => 'file_upload_help',
        '#description' => '',
        '#upload_validators' => $elements[0]['#upload_validators'],
        '#cardinality' => $cardinality,
      );
181 182 183 184 185 186
    }

    return $elements;
  }

  /**
187
   * {@inheritdoc}
188
   */
189
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, array &$form_state) {
190 191 192 193 194 195 196 197 198 199 200
    $field_settings = $this->getFieldSettings();

    // The field settings include defaults for the field type. However, this
    // widget is a base class for other widgets (e.g., ImageWidget) that may act
    // on field types without these expected settings.
    $field_settings += array(
      'display_default' => NULL,
      'display_field' => NULL,
      'description_field' => NULL,
    );

201
    $cardinality = $this->fieldDefinition->getCardinality();
202
    $defaults = array(
203
      'fids' => array(),
204
      'display' => (bool) $field_settings['display_default'],
205 206 207 208 209 210 211 212
      'description' => '',
    );

    // Essentially we use the managed_file type, extended with some
    // enhancements.
    $element_info = element_info('managed_file');
    $element += array(
      '#type' => 'managed_file',
213 214
      '#upload_location' => $items[$delta]->getUploadLocation(),
      '#upload_validators' => $items[$delta]->getUploadValidators(),
215 216
      '#value_callback' => array(get_class($this), 'value'),
      '#process' => array_merge($element_info['#process'], array(array(get_class($this), 'process'))),
217 218 219
      '#progress_indicator' => $this->getSetting('progress_indicator'),
      // Allows this field to return an array instead of a single value.
      '#extended' => TRUE,
220
      // Add properties needed by value() and process() methods.
221 222 223 224
      '#display_field' => (bool) $field_settings['display_field'],
      '#display_default' => $field_settings['display_default'],
      '#description_field' => $field_settings['description_field'],
      '#cardinality' => $cardinality,
225 226 227
    );

    $element['#weight'] = $delta;
228 229 230

    // Field stores FID value in a single mode, so we need to transform it for
    // form element to recognize it correctly.
231 232
    if (!isset($items[$delta]->fids) && isset($items[$delta]->target_id)) {
      $items[$delta]->fids = array($items[$delta]->target_id);
233
    }
234
    $element['#default_value'] = $items[$delta]->getValue() + $defaults;
235

236 237
    $default_fids = $element['#extended'] ? $element['#default_value']['fids'] : $element['#default_value'];
    if (empty($default_fids)) {
238 239 240 241 242 243 244
      $file_upload_help = array(
        '#theme' => 'file_upload_help',
        '#description' => $element['#description'],
        '#upload_validators' => $element['#upload_validators'],
        '#cardinality' => $cardinality,
      );
      $element['#description'] = drupal_render($file_upload_help);
245 246
      $element['#multiple'] = $cardinality != 1 ? TRUE : FALSE;
      if ($cardinality != 1 && $cardinality != -1) {
247
        $element['#element_validate'] = array(array(get_class($this), 'validateMultipleCount'));
248
      }
249 250 251 252 253
    }

    return $element;
  }

254
  /**
255
   * {@inheritdoc}
256 257 258 259 260 261 262 263 264
   */
  public function massageFormValues(array $values, array $form, array &$form_state) {
    // Since file upload widget now supports uploads of more than one file at a
    // time it always returns an array of fids. We have to translate this to a
    // single fid, as field expects single value.
    $new_values = array();
    foreach ($values as &$value) {
      foreach ($value['fids'] as $fid) {
        $new_value = $value;
265
        $new_value['target_id'] = $fid;
266 267 268 269 270 271 272 273
        unset($new_value['fids']);
        $new_values[] = $new_value;
      }
    }

    return $new_values;
  }

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  /**
   * Form API callback. Retrieves the value for the file_generic field element.
   *
   * This method is assigned as a #value_callback in formElement() method.
   */
  public static function value($element, $input = FALSE, $form_state) {
    if ($input) {
      // Checkboxes lose their value when empty.
      // If the display field is present make sure its unchecked value is saved.
      if (empty($input['display'])) {
        $input['display'] = $element['#display_field'] ? 0 : 1;
      }
    }

    // We depend on the managed file element to handle uploads.
    $return = file_managed_file_value($element, $input, $form_state);

    // Ensure that all the required properties are returned even if empty.
    $return += array(
      'fids' => array(),
      'display' => 1,
      'description' => '',
    );

    return $return;
  }

  /**
   * Form element validation callback for upload element on file widget. Checks
   * if user has uploaded more files than allowed.
   *
   * This validator is used only when cardinality not set to 1 or unlimited.
   */
  public static function validateMultipleCount($element, &$form_state, $form) {
    $parents = $element['#parents'];
    $values = NestedArray::getValue($form_state['values'], $parents);

    array_pop($parents);
312
    $current = count(Element::children(NestedArray::getValue($form, $parents))) - 1;
313

314 315
    $field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions($element['#entity_type']);
    $field = $field_storage_definitions[$element['#field_name']];
316 317
    $uploaded = count($values['fids']);
    $count = $uploaded + $current;
318 319
    if ($count > $field->getCardinality()) {
      $keep = $uploaded - $count + $field->getCardinality();
320 321 322 323 324 325
      $removed_files = array_slice($values['fids'], $keep);
      $removed_names = array();
      foreach ($removed_files as $fid) {
        $file = file_load($fid);
        $removed_names[] = $file->getFilename();
      }
326
      $args = array('%field' => $field->getFieldName(), '@max' => $field->getCardinality(), '@count' => $keep, '%list' => implode(', ', $removed_names));
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
      $message = t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args);
      drupal_set_message($message, 'warning');
      $values['fids'] = array_slice($values['fids'], 0, $keep);
      NestedArray::setValue($form_state['values'], $element['#parents'], $values);
    }
  }

  /**
   * Form API callback: Processes a file_generic field element.
   *
   * Expands the file_generic type to include the description and display
   * fields.
   *
   * This method is assigned as a #process callback in formElement() method.
   */
  public static function process($element, &$form_state, $form) {
    $item = $element['#value'];
    $item['fids'] = $element['fids']['#value'];

    $element['#theme'] = 'file_widget';

    // Add the display field if enabled.
    if ($element['#display_field'] && $item['fids']) {
      $element['display'] = array(
        '#type' => empty($item['fids']) ? 'hidden' : 'checkbox',
        '#title' => t('Include file in display'),
        '#value' => isset($item['display']) ? $item['display'] : $element['#display_default'],
        '#attributes' => array('class' => array('file-display')),
      );
    }
    else {
      $element['display'] = array(
        '#type' => 'hidden',
        '#value' => '1',
      );
    }

    // Add the description field if enabled.
    if ($element['#description_field'] && $item['fids']) {
      $config = \Drupal::config('file.settings');
      $element['description'] = array(
        '#type' => $config->get('description.type'),
        '#title' => t('Description'),
        '#value' => isset($item['description']) ? $item['description'] : '',
        '#maxlength' => $config->get('description.length'),
        '#description' => t('The description may be used as the label of the link to the file.'),
      );
    }

    // Adjust the Ajax settings so that on upload and remove of any individual
    // file, the entire group of file fields is updated together.
    if ($element['#cardinality'] != 1) {
      $parents = array_slice($element['#array_parents'], 0, -1);
      $new_path = 'file/ajax';
      $new_options = array(
        'query' => array(
          'element_parents' => implode('/', $parents),
          'form_build_id' => $form['form_build_id']['#value'],
        ),
      );
      $field_element = NestedArray::getValue($form, $parents);
      $new_wrapper = $field_element['#id'] . '-ajax-wrapper';
389
      foreach (Element::children($element) as $key) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        if (isset($element[$key]['#ajax'])) {
          $element[$key]['#ajax']['path'] = $new_path;
          $element[$key]['#ajax']['options'] = $new_options;
          $element[$key]['#ajax']['wrapper'] = $new_wrapper;
        }
      }
      unset($element['#prefix'], $element['#suffix']);
    }

    // Add another submit handler to the upload and remove buttons, to implement
    // functionality needed by the field widget. This submit handler, along with
    // the rebuild logic in file_field_widget_form() requires the entire field,
    // not just the individual item, to be valid.
    foreach (array('upload_button', 'remove_button') as $key) {
      $element[$key]['#submit'][] = array(get_called_class(), 'submit');
      $element[$key]['#limit_validation_errors'] = array(array_slice($element['#parents'], 0, -1));
    }

    return $element;
  }

  /**
   * 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.
   */
  public static function processMultiple($element, &$form_state, $form) {
421
    $element_children = Element::children($element, TRUE);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    $count = count($element_children);

    foreach ($element_children as $delta => $key) {
      if ($key != $element['#file_upload_delta']) {
        $description = static::getDescriptionFromElement($element[$key]);
        $element[$key]['_weight'] = array(
          '#type' => 'weight',
          '#title' => $description ? t('Weight for @title', array('@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'] = array(
          '#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;
  }

  /**
   * Retrieves the file description from a field field element.
   *
   * This helper static method is used by processMultiple() method.
   *
   * @param array $element
   *   An associative array with the element being processed.
   *
   * @return array|false
   *   A description of the file suitable for use in the administrative
   *   interface.
   */
  protected static function getDescriptionFromElement($element) {
    // Use the actual file description, if it's available.
    if (!empty($element['#default_value']['description'])) {
      return $element['#default_value']['description'];
    }
    // Otherwise, fall back to the filename.
    if (!empty($element['#default_value']['filename'])) {
      return $element['#default_value']['filename'];
    }
    // This is probably a newly uploaded file; no description is available.
    return FALSE;
  }

  /**
   * Form submission handler for upload/remove button of formElement().
   *
   * This runs in addition to and after file_managed_file_submit().
   *
   * @see file_managed_file_submit()
   */
  public static function submit($form, &$form_state) {
    // During the form rebuild, formElement() will create field item widget
    // elements using re-indexed deltas, so clear out $form_state['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.
    $parents = array_slice($form_state['triggering_element']['#parents'], 0, -2);
    NestedArray::setValue($form_state['input'], $parents, NULL);

    $button = $form_state['triggering_element'];

    // 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['values'], 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['values'], array_slice($button['#parents'], 0, -2), $submitted_values);

    // Update items.
    $field_state = field_form_get_state($parents, $field_name, $form_state);
    $field_state['items'] = $submitted_values;
    field_form_set_state($parents, $field_name, $form_state, $field_state);
  }

536
}