function WidgetBase::addMoreAjax

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Field/WidgetBase.php \Drupal\Core\Field\WidgetBase::addMoreAjax()
  2. 8.9.x core/lib/Drupal/Core/Field/WidgetBase.php \Drupal\Core\Field\WidgetBase::addMoreAjax()
  3. 11.x core/lib/Drupal/Core/Field/WidgetBase.php \Drupal\Core\Field\WidgetBase::addMoreAjax()

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.

File

core/lib/Drupal/Core/Field/WidgetBase.php, line 342

Class

WidgetBase
Base class for 'Field widget' plugin implementations.

Namespace

Drupal\Core\Field

Code

public static function addMoreAjax(array $form, FormStateInterface $form_state) {
  $button = $form_state->getTriggeringElement();
  // 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.
  if ($element['#cardinality'] != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
    return;
  }
  // Add a DIV around the delta receiving the Ajax effect.
  $delta = $element['#max_delta'];
  // Construct an attribute to add to div for use as selector to set the focus on.
  $button_parent = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
  $focus_attribute = 'data-drupal-selector="field-' . $button_parent['#field_name'] . '-more-focus-target"';
  $element[$delta]['#prefix'] = '<div class="ajax-new-content" ' . $focus_attribute . '>' . ($element[$delta]['#prefix'] ?? '');
  $element[$delta]['#suffix'] = ($element[$delta]['#suffix'] ?? '') . '</div>';
  // Turn render array into response with AJAX commands.
  $response = new AjaxResponse();
  $response->addCommand(new InsertCommand(NULL, $element));
  // Add command to set the focus on first focusable element within the div.
  $response->addCommand(new FocusFirstCommand("[{$focus_attribute}]"));
  return $response;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.