WidgetBase.php 20 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Field;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\NestedArray;
7
use Drupal\Component\Utility\SortArray;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\Core\Render\Element;
10
use Symfony\Component\Validator\ConstraintViolationInterface;
11
use Symfony\Component\Validator\ConstraintViolationListInterface;
12 13 14

/**
 * Base class for 'Field widget' plugin implementations.
15 16
 *
 * @ingroup field_widget
17 18 19
 */
abstract class WidgetBase extends PluginSettingsBase implements WidgetInterface {

20 21
  use AllowedTagsXssTrait;

22 23 24
  /**
   * The field definition.
   *
25
   * @var \Drupal\Core\Field\FieldDefinitionInterface
26
   */
27
  protected $fieldDefinition;
28 29 30 31 32 33 34 35 36 37 38 39 40

  /**
   * The widget settings.
   *
   * @var array
   */
  protected $settings;

  /**
   * Constructs a WidgetBase object.
   *
   * @param array $plugin_id
   *   The plugin_id for the widget.
41
   * @param mixed $plugin_definition
42
   *   The plugin implementation definition.
43
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
44
   *   The definition of the field to which the widget is associated.
45 46
   * @param array $settings
   *   The widget settings.
47
   * @param array $third_party_settings
48
   *   Any third party settings.
49
   */
50
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings) {
51
    parent::__construct(array(), $plugin_id, $plugin_definition);
52
    $this->fieldDefinition = $field_definition;
53
    $this->settings = $settings;
54
    $this->thirdPartySettings = $third_party_settings;
55 56 57
  }

  /**
58
   * {@inheritdoc}
59
   */
60
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
61
    $field_name = $this->fieldDefinition->getName();
62 63 64
    $parents = $form['#parents'];

    // Store field information in $form_state.
65
    if (!static::getWidgetState($parents, $field_name, $form_state)) {
66
      $field_state = array(
67 68
        'items_count' => count($items),
        'array_parents' => array(),
69
      );
70
      static::setWidgetState($parents, $field_name, $form_state, $field_state);
71 72 73 74 75 76 77 78
    }

    // Collect widget elements.
    $elements = array();

    // If the widget is handling multiple values (e.g Options), or if we are
    // displaying an individual element, just get a single form element and make
    // it the $delta value.
79
    if ($this->handlesMultipleValues() || isset($get_delta)) {
80 81
      $delta = isset($get_delta) ? $get_delta : 0;
      $element = array(
82
        '#title' => $this->fieldDefinition->getLabel(),
83
        '#description' => FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription())),
84
      );
85
      $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

      if ($element) {
        if (isset($get_delta)) {
          // If we are processing a specific delta value for a field where the
          // field module handles multiples, set the delta in the result.
          $elements[$delta] = $element;
        }
        else {
          // For fields that handle their own processing, we cannot make
          // assumptions about how the field is structured, just merge in the
          // returned element.
          $elements = $element;
        }
      }
    }
    // If the widget does not handle multiple values itself, (and we are not
    // displaying an individual element), process the multiple value form.
    else {
104
      $elements = $this->formMultipleElements($items, $form, $form_state);
105 106
    }

107 108
    // Populate the 'array_parents' information in $form_state->get('field')
    // after the form is built, so that we catch changes in the form structure
109 110
    // performed in alter() hooks.
    $elements['#after_build'][] = array(get_class($this), 'afterBuild');
111 112
    $elements['#field_name'] = $field_name;
    $elements['#field_parents'] = $parents;
113 114 115 116 117
    // Enforce the structure of submitted values.
    $elements['#parents'] = array_merge($parents, array($field_name));
    // Most widgets need their internal structure preserved in submitted values.
    $elements += array('#tree' => TRUE);

118 119 120 121 122 123 124
    return array(
      // Aid in theming of widgets by rendering a classified container.
      '#type' => 'container',
      // Assign a different parent, to keep the main id for the widget itself.
      '#parents' => array_merge($parents, array($field_name . '_wrapper')),
      '#attributes' => array(
        'class' => array(
125 126 127
          'field--type-' . Html::getClass($this->fieldDefinition->getType()),
          'field--name-' . Html::getClass($field_name),
          'field--widget-' . Html::getClass($this->getPluginId()),
128 129
        ),
      ),
130
      'widget' => $elements,
131 132 133 134 135 136 137 138 139 140 141
    );
  }

  /**
   * Special handling to create form elements for multiple values.
   *
   * Handles generic features for multiple fields:
   * - number of widgets
   * - AHAH-'add more' button
   * - table display and drag-n-drop value reordering
   */
142
  protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
143
    $field_name = $this->fieldDefinition->getName();
144
    $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
145 146 147
    $parents = $form['#parents'];

    // Determine the number of widgets to display.
148
    switch ($cardinality) {
149
      case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
150
        $field_state = static::getWidgetState($parents, $field_name, $form_state);
151 152 153 154 155
        $max = $field_state['items_count'];
        $is_multiple = TRUE;
        break;

      default:
156 157
        $max = $cardinality - 1;
        $is_multiple = ($cardinality > 1);
158 159 160
        break;
    }

161
    $title = $this->fieldDefinition->getLabel();
162
    $description = FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));
163 164 165 166

    $elements = array();

    for ($delta = 0; $delta <= $max; $delta++) {
167 168 169 170 171
      // Add a new empty item if it doesn't exist yet at this delta.
      if (!isset($items[$delta])) {
        $items->appendItem();
      }

172 173
      // For multiple fields, title and description are handled by the wrapping
      // table.
174 175
      if ($is_multiple) {
        $element = [
176
          '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
177 178 179 180 181 182 183 184 185 186 187 188
          '#title_display' => 'invisible',
          '#description' => '',
        ];
      }
      else {
        $element = [
          '#title' => $title,
          '#title_display' => 'before',
          '#description' => $description,
        ];
      }

189
      $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
190 191 192 193 194 195 196 197

      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',
198
            '#title' => $this->t('Weight for row @number', array('@number' => $delta + 1)),
199 200 201
            '#title_display' => 'invisible',
            // Note: this 'delta' is the FAPI #type 'weight' element's property.
            '#delta' => $max,
202
            '#default_value' => $items[$delta]->_weight ?: $delta,
203 204 205 206 207 208 209 210 211 212 213
            '#weight' => 100,
          );
        }

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

    if ($elements) {
      $elements += array(
        '#theme' => 'field_multiple_value_form',
214 215
        '#field_name' => $field_name,
        '#cardinality' => $cardinality,
216
        '#cardinality_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
217
        '#required' => $this->fieldDefinition->isRequired(),
218 219 220 221 222 223
        '#title' => $title,
        '#description' => $description,
        '#max_delta' => $max,
      );

      // Add 'add more' button, if not working with a programmed form.
224
      if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && !$form_state->isProgrammed()) {
225
        $id_prefix = implode('-', array_merge($parents, array($field_name)));
226
        $wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
227 228 229
        $elements['#prefix'] = '<div id="' . $wrapper_id . '">';
        $elements['#suffix'] = '</div>';

230 231 232 233 234
        $elements['add_more'] = array(
          '#type' => 'submit',
          '#name' => strtr($id_prefix, '-', '_') . '_add_more',
          '#value' => t('Add another item'),
          '#attributes' => array('class' => array('field-add-more-submit')),
235
          '#limit_validation_errors' => array(array_merge($parents, array($field_name))),
236
          '#submit' => array(array(get_class($this), 'addMoreSubmit')),
237
          '#ajax' => array(
238 239 240
            'callback' => array(get_class($this), 'addMoreAjax'),
            'wrapper' => $wrapper_id,
            'effect' => 'fade',
241 242 243 244 245 246 247 248
          ),
        );
      }
    }

    return $elements;
  }

249 250 251 252 253 254
  /**
   * After-build handler for field elements in a form.
   *
   * This stores the final location of the field within the form structure so
   * that flagErrors() can assign validation errors to the right form element.
   */
255
  public static function afterBuild(array $element, FormStateInterface $form_state) {
256 257 258 259 260 261 262 263 264 265
    $parents = $element['#field_parents'];
    $field_name = $element['#field_name'];

    $field_state = static::getWidgetState($parents, $field_name, $form_state);
    $field_state['array_parents'] = $element['#array_parents'];
    static::setWidgetState($parents, $field_name, $form_state, $field_state);

    return $element;
  }

266 267 268
  /**
   * Submission handler for the "Add another item" button.
   */
269
  public static function addMoreSubmit(array $form, FormStateInterface $form_state) {
270
    $button = $form_state->getTriggeringElement();
271 272 273 274 275 276 277

    // 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'];

    // Increment the items count.
278
    $field_state = static::getWidgetState($parents, $field_name, $form_state);
279
    $field_state['items_count']++;
280
    static::setWidgetState($parents, $field_name, $form_state, $field_state);
281

282
    $form_state->setRebuild();
283 284 285 286 287 288 289 290
  }

  /**
   * Ajax callback for the "Add another item" button.
   *
   * This returns the new page content to replace the page content made obsolete
   * by the form submission.
   */
291
  public static function addMoreAjax(array $form, FormStateInterface $form_state) {
292
    $button = $form_state->getTriggeringElement();
293 294 295 296 297

    // Go one level up in the form, to the widgets container.
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));

    // Ensure the widget allows adding additional items.
298
    if ($element['#cardinality'] != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
299 300 301 302 303 304 305 306 307 308 309
      return;
    }

    // Add a DIV around the delta receiving the Ajax effect.
    $delta = $element['#max_delta'];
    $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
    $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';

    return $element;
  }

310 311 312
  /**
   * Generates the form element for a single copy of the widget.
   */
313
  protected function formSingleElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
314 315
    $entity = $items->getEntity();

316 317 318
    $element += array(
      '#field_parents' => $form['#parents'],
      // Only the first widget should be required.
319
      '#required' => $delta == 0 && $this->fieldDefinition->isRequired(),
320 321 322 323
      '#delta' => $delta,
      '#weight' => $delta,
    );

324
    $element = $this->formElement($items, $delta, $element, $form, $form_state);
325 326 327 328 329

    if ($element) {
      // Allow modules to alter the field widget form element.
      $context = array(
        'form' => $form,
330
        'widget' => $this,
331 332
        'items' => $items,
        'delta' => $delta,
333
        'default' => $this->isDefaultValueWidget($form_state),
334
      );
335
      \Drupal::moduleHandler()->alter(array('field_widget_form', 'field_widget_' . $this->getPluginId() . '_form'), $element, $form_state, $context);
336 337 338 339 340 341
    }

    return $element;
  }

  /**
342
   * {@inheritdoc}
343
   */
344
  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
345
    $field_name = $this->fieldDefinition->getName();
346

347
    // Extract the values from $form_state->getValues().
348
    $path = array_merge($form['#parents'], array($field_name));
349
    $key_exists = NULL;
350
    $values = NestedArray::getValue($form_state->getValues(), $path, $key_exists);
351 352

    if ($key_exists) {
353 354 355 356 357 358
      // Account for drag-and-drop reordering if needed.
      if (!$this->handlesMultipleValues()) {
        // Remove the 'value' of the 'add more' button.
        unset($values['add_more']);

        // The original delta, before drag-and-drop reordering, is needed to
359
        // route errors to the correct form element.
360 361
        foreach ($values as $delta => &$value) {
          $value['_original_delta'] = $delta;
362 363
        }

364 365 366
        usort($values, function ($a, $b) {
          return SortArray::sortByKeyInt($a, $b, '_weight');
        });
367 368
      }

369 370
      // Let the widget massage the submitted values.
      $values = $this->massageFormValues($values, $form, $form_state);
371

372 373
      // Assign the values and remove the empty ones.
      $items->setValue($values);
374
      $items->filterEmptyItems();
375 376

      // Put delta mapping in $form_state, so that flagErrors() can use it.
377
      $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
378
      foreach ($items as $delta => $item) {
379 380
        $field_state['original_deltas'][$delta] = isset($item->_original_delta) ? $item->_original_delta : $delta;
        unset($item->_original_delta, $item->_weight);
381
      }
382
      static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
383 384 385 386
    }
  }

  /**
387
   * {@inheritdoc}
388
   */
389
  public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
390
    $field_name = $this->fieldDefinition->getName();
391

392
    $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
393

394
    if ($violations->count()) {
395
      // Locate the correct element in the form.
396
      $element = NestedArray::getValue($form_state->getCompleteForm(), $field_state['array_parents']);
397

398 399 400
      // Do not report entity-level validation errors if Form API errors have
      // already been reported for the field.
      // @todo Field validation should not be run on fields with FAPI errors to
401
      //   begin with. See https://www.drupal.org/node/2070429.
402
      $element_path = implode('][', $element['#parents']);
403
      if ($reported_errors = $form_state->getErrors()) {
404 405 406 407 408 409 410
        foreach (array_keys($reported_errors) as $error_path) {
          if (strpos($error_path, $element_path) === 0) {
            return;
          }
        }
      }

411 412
      // Only set errors if the element is visible.
      if (Element::isVisibleElement($element)) {
413
        $handles_multiple = $this->handlesMultipleValues();
414

415
        $violations_by_delta = array();
416
        foreach ($violations as $violation) {
417 418 419 420
          // Separate violations by delta.
          $property_path = explode('.', $violation->getPropertyPath());
          $delta = array_shift($property_path);
          $violations_by_delta[$delta][] = $violation;
421
          $violation->arrayPropertyPath = $property_path;
422 423
        }

424
        /** @var \Symfony\Component\Validator\ConstraintViolationInterface[] $delta_violations */
425
        foreach ($violations_by_delta as $delta => $delta_violations) {
426 427 428
          // Pass violations to the main element:
          // - if this is a multiple-value widget,
          // - or if the violations are at the ItemList level.
429
          if ($handles_multiple || !is_numeric($delta)) {
430 431
            $delta_element = $element;
          }
432
          // Otherwise, pass errors by delta to the corresponding sub-element.
433 434 435 436
          else {
            $original_delta = $field_state['original_deltas'][$delta];
            $delta_element = $element[$original_delta];
          }
437 438 439
          foreach ($delta_violations as $violation) {
            // @todo: Pass $violation->arrayPropertyPath as property path.
            $error_element = $this->errorElement($delta_element, $violation, $form, $form_state);
440
            if ($error_element !== FALSE) {
441
              $form_state->setError($error_element, $violation->getMessage());
442
            }
443 444 445 446 447 448
          }
        }
      }
    }
  }

449 450 451
  /**
   * {@inheritdoc}
   */
452
  public static function getWidgetState(array $parents, $field_name, FormStateInterface $form_state) {
453
    return NestedArray::getValue($form_state->getStorage(), static::getWidgetStateParents($parents, $field_name));
454 455 456 457 458
  }

  /**
   * {@inheritdoc}
   */
459
  public static function setWidgetState(array $parents, $field_name, FormStateInterface $form_state, array $field_state) {
460
    NestedArray::setValue($form_state->getStorage(), static::getWidgetStateParents($parents, $field_name), $field_state);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  }

  /**
   * Returns the location of processing information within $form_state.
   *
   * @param array $parents
   *   The array of #parents where the widget lives in the form.
   * @param string $field_name
   *   The field name.
   *
   * @return array
   *   The location of processing information within $form_state.
   */
  protected static function getWidgetStateParents(array $parents, $field_name) {
    // Field processing data is placed at
476
    // $form_state->get(['field_storage', '#parents', ...$parents..., '#fields', $field_name]),
477
    // to avoid clashes between field names and $parents parts.
478
    return array_merge(array('field_storage', '#parents'), $parents, array('#fields', $field_name));
479 480
  }

481
  /**
482
   * {@inheritdoc}
483
   */
484
  public function settingsForm(array $form, FormStateInterface $form_state) {
485 486 487
    return array();
  }

488 489 490 491 492 493 494
  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    return array();
  }

495
  /**
496
   * {@inheritdoc}
497
   */
498
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
499 500 501 502
    return $element;
  }

  /**
503
   * {@inheritdoc}
504
   */
505
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
506 507 508
    return $values;
  }

509 510 511 512 513 514 515
  /**
   * Returns the array of field settings.
   *
   * @return array
   *   The array of settings.
   */
  protected function getFieldSettings() {
516
    return $this->fieldDefinition->getSettings();
517 518 519 520 521 522 523 524 525 526 527 528
  }

  /**
   * Returns the value of a field setting.
   *
   * @param string $setting_name
   *   The setting name.
   *
   * @return mixed
   *   The setting value.
   */
  protected function getFieldSetting($setting_name) {
529
    return $this->fieldDefinition->getSetting($setting_name);
530 531
  }

532 533 534 535 536 537 538 539 540 541 542 543
  /**
   * Returns whether the widget handles multiple values.
   *
   * @return bool
   *   TRUE if a single copy of formElement() can handle multiple field values,
   *   FALSE if multiple values require separate copies of formElement().
   */
  protected function handlesMultipleValues() {
    $definition = $this->getPluginDefinition();
    return $definition['multiple_values'];
  }

544 545 546 547 548 549 550 551
  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    // By default, widgets are available for all fields.
    return TRUE;
  }

552 553 554 555 556 557 558 559 560 561 562 563 564
  /**
   * Returns whether the widget used for default value form.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return bool
   *   TRUE if a widget used to input default value, FALSE otherwise.
   */
  protected function isDefaultValueWidget(FormStateInterface $form_state) {
    return (bool) $form_state->get('default_value_widget');
  }

565 566 567 568 569 570 571 572 573 574
  /**
   * Returns the filtered field description.
   *
   * @return \Drupal\Core\Field\FieldFilteredMarkup
   *   The filtered field description, with tokens replaced.
   */
  protected function getFilteredDescription() {
    return FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));
  }

575
}