function ListItemBase::addMoreAjax

Same name and namespace in other branches
  1. 10 core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php \Drupal\options\Plugin\Field\FieldType\ListItemBase::addMoreAjax()

Ajax callback for the "Add another item" button.

File

core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php, line 266

Class

ListItemBase
Plugin base class inherited by the options field types.

Namespace

Drupal\options\Plugin\Field\FieldType

Code

public static function addMoreAjax(array $form, FormStateInterface $form_state) {
    $button = $form_state->getTriggeringElement();
    // Go one level up in the form.
    $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
    $delta = $element['table']['#max_delta'];
    $element['table'][$delta]['item']['#prefix'] = '<div class="ajax-new-content" data-drupal-selector="field-list-add-more-focus-target">' . ($element['table'][$delta]['item']['#prefix'] ?? '');
    $element['table'][$delta]['item']['#suffix'] = ($element['table'][$delta]['item']['#suffix'] ?? '') . '</div>';
    // Enable the remove button for the first row if there are more rows.
    if ($delta > 0 && isset($element['table'][0]['delete']['#attributes']['disabled']) && !isset($element['table'][0]['item']['key']['#attributes']['disabled'])) {
        unset($element['table'][0]['delete']['#attributes']['disabled']);
    }
    $response = new AjaxResponse();
    $response->addCommand(new InsertCommand(NULL, $element));
    $response->addCommand(new FocusFirstCommand('[data-drupal-selector="field-list-add-more-focus-target"]'));
    return $response;
}

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