You are here

protected function InlineEntityFormSimple::formMultipleElements in Inline Entity Form 8

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

Overrides WidgetBase::formMultipleElements

File

src/Plugin/Field/FieldWidget/InlineEntityFormSimple.php, line 87

Class

InlineEntityFormSimple
Simple inline widget.

Namespace

Drupal\inline_entity_form\Plugin\Field\FieldWidget

Code

protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
  $element = parent::formMultipleElements($items, $form, $form_state);

  // If we're using unlimited cardinality we don't display one empty item.
  // Form validation will kick in if left empty which essentially means
  // people won't be able to submit without creating another entity.
  if (!$form_state
    ->isSubmitted() && $element['#cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && $element['#max_delta'] > 0) {
    $max = $element['#max_delta'];
    unset($element[$max]);
    $element['#max_delta'] = $max - 1;
    $items
      ->removeItem($max);

    // Decrement the items count.
    $field_name = $element['#field_name'];
    $parents = $element[0]['#field_parents'];
    $field_state = static::getWidgetState($parents, $field_name, $form_state);
    $field_state['items_count']--;
    static::setWidgetState($parents, $field_name, $form_state, $field_state);
  }

  // Remove add options if the user cannot add new entities.
  if (!$this
    ->canAddNew()) {
    if (isset($element['add_more'])) {
      unset($element['add_more']);
    }
    foreach (Element::children($element) as $delta) {
      if (isset($element[$delta]['inline_entity_form'])) {
        if ($element[$delta]['inline_entity_form']['#op'] == 'add') {
          unset($element[$delta]);
        }
      }
    }
  }
  return $element;
}