3 namespace Drupal\Core\Field;
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;
14 * Base class for 'Field widget' plugin implementations.
16 * @ingroup field_widget
18 abstract class WidgetBase extends PluginSettingsBase implements WidgetInterface {
20 use AllowedTagsXssTrait;
23 * The field definition.
25 * @var \Drupal\Core\Field\FieldDefinitionInterface
27 protected $fieldDefinition;
30 * The widget settings.
37 * Constructs a WidgetBase object.
39 * @param string $plugin_id
40 * 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 * @param array $settings
46 * The widget settings.
47 * @param array $third_party_settings
48 * Any third party settings.
50 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings) {
51 parent::__construct([], $plugin_id, $plugin_definition);
52 $this->fieldDefinition = $field_definition;
53 $this->settings = $settings;
54 $this->thirdPartySettings = $third_party_settings;
60 public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
61 $field_name = $this->fieldDefinition->getName();
62 $parents = $form['#parents'];
64 // Store field information in $form_state.
65 if (!static::getWidgetState($parents, $field_name, $form_state)) {
67 'items_count' => count($items),
68 'array_parents' => [],
70 static::setWidgetState($parents, $field_name, $form_state, $field_state);
73 // Collect widget elements.
76 // If the widget is handling multiple values (e.g Options), or if we are
77 // displaying an individual element, just get a single form element and make
78 // it the $delta value.
79 if ($this->handlesMultipleValues() || isset($get_delta)) {
80 $delta = isset($get_delta) ? $get_delta : 0;
82 '#title' => $this->fieldDefinition->getLabel(),
83 '#description' => FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription())),
85 $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
88 if (isset($get_delta)) {
89 // If we are processing a specific delta value for a field where the
90 // field module handles multiples, set the delta in the result.
91 $elements[$delta] = $element;
94 // For fields that handle their own processing, we cannot make
95 // assumptions about how the field is structured, just merge in the
101 // If the widget does not handle multiple values itself, (and we are not
102 // displaying an individual element), process the multiple value form.
104 $elements = $this->formMultipleElements($items, $form, $form_state);
107 // Allow modules to alter the field multi-value widget form element.
108 // This hook can also be used for single-value fields.
113 'default' => $this->isDefaultValueWidget($form_state),
115 \Drupal::moduleHandler()->alter([
116 'field_widget_multivalue_form',
117 'field_widget_multivalue_' . $this->getPluginId() . '_form',
118 ], $elements, $form_state, $context);
120 // Populate the 'array_parents' information in $form_state->get('field')
121 // after the form is built, so that we catch changes in the form structure
122 // performed in alter() hooks.
123 $elements['#after_build'][] = [get_class($this), 'afterBuild'];
124 $elements['#field_name'] = $field_name;
125 $elements['#field_parents'] = $parents;
126 // Enforce the structure of submitted values.
127 $elements['#parents'] = array_merge($parents, [$field_name]);
128 // Most widgets need their internal structure preserved in submitted values.
129 $elements += ['#tree' => TRUE];
132 // Aid in theming of widgets by rendering a classified container.
133 '#type' => 'container',
134 // Assign a different parent, to keep the main id for the widget itself.
135 '#parents' => array_merge($parents, [$field_name . '_wrapper']),
138 'field--type-' . Html::getClass($this->fieldDefinition->getType()),
139 'field--name-' . Html::getClass($field_name),
140 'field--widget-' . Html::getClass($this->getPluginId()),
143 'widget' => $elements,
148 * Special handling to create form elements for multiple values.
150 * Handles generic features for multiple fields:
151 * - number of widgets
152 * - AHAH-'add more' button
153 * - table display and drag-n-drop value reordering
155 protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
156 $field_name = $this->fieldDefinition->getName();
157 $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
158 $parents = $form['#parents'];
160 // Determine the number of widgets to display.
161 switch ($cardinality) {
162 case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
163 $field_state = static::getWidgetState($parents, $field_name, $form_state);
164 $max = $field_state['items_count'];
169 $max = $cardinality - 1;
170 $is_multiple = ($cardinality > 1);
174 $title = $this->fieldDefinition->getLabel();
175 $description = FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));
179 for ($delta = 0; $delta <= $max; $delta++) {
180 // Add a new empty item if it doesn't exist yet at this delta.
181 if (!isset($items[$delta])) {
182 $items->appendItem();
185 // For multiple fields, title and description are handled by the wrapping
189 '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
190 '#title_display' => 'invisible',
191 '#description' => '',
197 '#title_display' => 'before',
198 '#description' => $description,
202 $element = $this->formSingleElement($items, $delta, $element, $form, $form_state);
205 // Input field for the delta (drag-n-drop reordering).
207 // We name the element '_weight' to avoid clashing with elements
208 // defined by widget.
209 $element['_weight'] = [
211 '#title' => $this->t('Weight for row @number', ['@number' => $delta + 1]),
212 '#title_display' => 'invisible',
213 // Note: this 'delta' is the FAPI #type 'weight' element's property.
215 '#default_value' => $items[$delta]->_weight ?: $delta,
220 $elements[$delta] = $element;
226 '#theme' => 'field_multiple_value_form',
227 '#field_name' => $field_name,
228 '#cardinality' => $cardinality,
229 '#cardinality_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
230 '#required' => $this->fieldDefinition->isRequired(),
232 '#description' => $description,
233 '#max_delta' => $max,
236 // Add 'add more' button, if not working with a programmed form.
237 if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && !$form_state->isProgrammed()) {
238 $id_prefix = implode('-', array_merge($parents, [$field_name]));
239 $wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
240 $elements['#prefix'] = '<div id="' . $wrapper_id . '">';
241 $elements['#suffix'] = '</div>';
243 $elements['add_more'] = [
245 '#name' => strtr($id_prefix, '-', '_') . '_add_more',
246 '#value' => t('Add another item'),
247 '#attributes' => ['class' => ['field-add-more-submit']],
248 '#limit_validation_errors' => [array_merge($parents, [$field_name])],
249 '#submit' => [[get_class($this), 'addMoreSubmit']],
251 'callback' => [get_class($this), 'addMoreAjax'],
252 'wrapper' => $wrapper_id,
263 * After-build handler for field elements in a form.
265 * This stores the final location of the field within the form structure so
266 * that flagErrors() can assign validation errors to the right form element.
268 public static function afterBuild(array $element, FormStateInterface $form_state) {
269 $parents = $element['#field_parents'];
270 $field_name = $element['#field_name'];
272 $field_state = static::getWidgetState($parents, $field_name, $form_state);
273 $field_state['array_parents'] = $element['#array_parents'];
274 static::setWidgetState($parents, $field_name, $form_state, $field_state);
280 * Submission handler for the "Add another item" button.
282 public static function addMoreSubmit(array $form, FormStateInterface $form_state) {
283 $button = $form_state->getTriggeringElement();
285 // Go one level up in the form, to the widgets container.
286 $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
287 $field_name = $element['#field_name'];
288 $parents = $element['#field_parents'];
290 // Increment the items count.
291 $field_state = static::getWidgetState($parents, $field_name, $form_state);
292 $field_state['items_count']++;
293 static::setWidgetState($parents, $field_name, $form_state, $field_state);
295 $form_state->setRebuild();
299 * Ajax callback for the "Add another item" button.
301 * This returns the new page content to replace the page content made obsolete
302 * by the form submission.
304 public static function addMoreAjax(array $form, FormStateInterface $form_state) {
305 $button = $form_state->getTriggeringElement();
307 // Go one level up in the form, to the widgets container.
308 $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
310 // Ensure the widget allows adding additional items.
311 if ($element['#cardinality'] != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
315 // Add a DIV around the delta receiving the Ajax effect.
316 $delta = $element['#max_delta'];
317 $element[$delta]['#prefix'] = '<div class="ajax-new-content">' . (isset($element[$delta]['#prefix']) ? $element[$delta]['#prefix'] : '');
318 $element[$delta]['#suffix'] = (isset($element[$delta]['#suffix']) ? $element[$delta]['#suffix'] : '') . '</div>';
324 * Generates the form element for a single copy of the widget.
326 protected function formSingleElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
328 '#field_parents' => $form['#parents'],
329 // Only the first widget should be required.
330 '#required' => $delta == 0 && $this->fieldDefinition->isRequired(),
335 $element = $this->formElement($items, $delta, $element, $form, $form_state);
338 // Allow modules to alter the field widget form element.
344 'default' => $this->isDefaultValueWidget($form_state),
346 \Drupal::moduleHandler()->alter(['field_widget_form', 'field_widget_' . $this->getPluginId() . '_form'], $element, $form_state, $context);
355 public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
356 $field_name = $this->fieldDefinition->getName();
358 // Extract the values from $form_state->getValues().
359 $path = array_merge($form['#parents'], [$field_name]);
361 $values = NestedArray::getValue($form_state->getValues(), $path, $key_exists);
364 // Account for drag-and-drop reordering if needed.
365 if (!$this->handlesMultipleValues()) {
366 // Remove the 'value' of the 'add more' button.
367 unset($values['add_more']);
369 // The original delta, before drag-and-drop reordering, is needed to
370 // route errors to the correct form element.
371 foreach ($values as $delta => &$value) {
372 $value['_original_delta'] = $delta;
375 usort($values, function ($a, $b) {
376 return SortArray::sortByKeyInt($a, $b, '_weight');
380 // Let the widget massage the submitted values.
381 $values = $this->massageFormValues($values, $form, $form_state);
383 // Assign the values and remove the empty ones.
384 $items->setValue($values);
385 $items->filterEmptyItems();
387 // Put delta mapping in $form_state, so that flagErrors() can use it.
388 $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
389 foreach ($items as $delta => $item) {
390 $field_state['original_deltas'][$delta] = isset($item->_original_delta) ? $item->_original_delta : $delta;
391 unset($item->_original_delta, $item->_weight);
393 static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
400 public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
401 $field_name = $this->fieldDefinition->getName();
403 $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
405 if ($violations->count()) {
406 // Locate the correct element in the form.
407 $element = NestedArray::getValue($form_state->getCompleteForm(), $field_state['array_parents']);
409 // Do not report entity-level validation errors if Form API errors have
410 // already been reported for the field.
411 // @todo Field validation should not be run on fields with FAPI errors to
412 // begin with. See https://www.drupal.org/node/2070429.
413 $element_path = implode('][', $element['#parents']);
414 if ($reported_errors = $form_state->getErrors()) {
415 foreach (array_keys($reported_errors) as $error_path) {
416 if (strpos($error_path, $element_path) === 0) {
422 // Only set errors if the element is visible.
423 if (Element::isVisibleElement($element)) {
424 $handles_multiple = $this->handlesMultipleValues();
426 $violations_by_delta = $item_list_violations = [];
427 foreach ($violations as $violation) {
428 // Separate violations by delta.
429 $property_path = explode('.', $violation->getPropertyPath());
430 $delta = array_shift($property_path);
431 if (is_numeric($delta)) {
432 $violations_by_delta[$delta][] = $violation;
434 // Violations at the ItemList level are not associated to any delta.
436 $item_list_violations[] = $violation;
438 $violation->arrayPropertyPath = $property_path;
441 /** @var \Symfony\Component\Validator\ConstraintViolationInterface[] $delta_violations */
442 foreach ($violations_by_delta as $delta => $delta_violations) {
443 // Pass violations to the main element if this is a multiple-value
445 if ($handles_multiple) {
446 $delta_element = $element;
448 // Otherwise, pass errors by delta to the corresponding sub-element.
450 $original_delta = $field_state['original_deltas'][$delta];
451 $delta_element = $element[$original_delta];
453 foreach ($delta_violations as $violation) {
454 // @todo: Pass $violation->arrayPropertyPath as property path.
455 $error_element = $this->errorElement($delta_element, $violation, $form, $form_state);
456 if ($error_element !== FALSE) {
457 $form_state->setError($error_element, $violation->getMessage());
462 /** @var \Symfony\Component\Validator\ConstraintViolationInterface[] $item_list_violations */
463 // Pass violations to the main element without going through
464 // errorElement() if the violations are at the ItemList level.
465 foreach ($item_list_violations as $violation) {
466 $form_state->setError($element, $violation->getMessage());
475 public static function getWidgetState(array $parents, $field_name, FormStateInterface $form_state) {
476 return NestedArray::getValue($form_state->getStorage(), static::getWidgetStateParents($parents, $field_name));
482 public static function setWidgetState(array $parents, $field_name, FormStateInterface $form_state, array $field_state) {
483 NestedArray::setValue($form_state->getStorage(), static::getWidgetStateParents($parents, $field_name), $field_state);
487 * Returns the location of processing information within $form_state.
489 * @param array $parents
490 * The array of #parents where the widget lives in the form.
491 * @param string $field_name
495 * The location of processing information within $form_state.
497 protected static function getWidgetStateParents(array $parents, $field_name) {
498 // Field processing data is placed at
499 // $form_state->get(['field_storage', '#parents', ...$parents..., '#fields', $field_name]),
500 // to avoid clashes between field names and $parents parts.
501 return array_merge(['field_storage', '#parents'], $parents, ['#fields', $field_name]);
507 public function settingsForm(array $form, FormStateInterface $form_state) {
514 public function settingsSummary() {
521 public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
528 public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
533 * Returns the array of field settings.
536 * The array of settings.
538 protected function getFieldSettings() {
539 return $this->fieldDefinition->getSettings();
543 * Returns the value of a field setting.
545 * @param string $setting_name
551 protected function getFieldSetting($setting_name) {
552 return $this->fieldDefinition->getSetting($setting_name);
556 * Returns whether the widget handles multiple values.
559 * TRUE if a single copy of formElement() can handle multiple field values,
560 * FALSE if multiple values require separate copies of formElement().
562 protected function handlesMultipleValues() {
563 $definition = $this->getPluginDefinition();
564 return $definition['multiple_values'];
570 public static function isApplicable(FieldDefinitionInterface $field_definition) {
571 // By default, widgets are available for all fields.
576 * Returns whether the widget used for default value form.
578 * @param \Drupal\Core\Form\FormStateInterface $form_state
579 * The current state of the form.
582 * TRUE if a widget used to input default value, FALSE otherwise.
584 protected function isDefaultValueWidget(FormStateInterface $form_state) {
585 return (bool) $form_state->get('default_value_widget');
589 * Returns the filtered field description.
591 * @return \Drupal\Core\Field\FieldFilteredMarkup
592 * The filtered field description, with tokens replaced.
594 protected function getFilteredDescription() {
595 return FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));