You are here

public static function YamlFormMultiple::addItemSubmit in YAML Form 8

Form submission handler for adding an item.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

src/Element/YamlFormMultiple.php, line 334

Class

YamlFormMultiple
Provides a form element to assist in creation of multiple elements.

Namespace

Drupal\yamlform\Element

Code

public static function addItemSubmit(array &$form, FormStateInterface $form_state) {
  $button = $form_state
    ->getTriggeringElement();
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -4));

  // Add item.
  $values = [];
  foreach ($element['items']['#value'] as $row_index => $value) {
    $values[] = $value;
    if ($row_index == $button['#row_index']) {
      $values[] = [
        'item' => '',
        'text' => '',
      ];
    }
  }

  // Add one item to the 'number of items'.
  $number_of_items_storage_key = self::getStorageKey($element, 'number_of_items');
  $number_of_items = $form_state
    ->get($number_of_items_storage_key);
  $form_state
    ->set($number_of_items_storage_key, $number_of_items + 1);

  // Reset values.
  $form_state
    ->setValueForElement($element['items'], $values);
  NestedArray::setValue($form_state
    ->getUserInput(), $element['items']['#parents'], $values);

  // Rebuild the form.
  $form_state
    ->setRebuild();
}