You are here

protected function FieldCollectionEmbedWidget::formMultipleElements in Field collection 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php \Drupal\field_collection\Plugin\Field\FieldWidget\FieldCollectionEmbedWidget::formMultipleElements()

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/FieldCollectionEmbedWidget.php, line 104

Class

FieldCollectionEmbedWidget
Plugin implementation of the 'field_collection_embed' widget.

Namespace

Drupal\field_collection\Plugin\Field\FieldWidget

Code

protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {

  // We don't want to render empty items on field collection fields
  // unless a) the field collection is empty ; b) the form is rebuilding,
  // which means that the user clicked on "Add another item"; or
  // c) we are creating a new entity.
  if (count($items) > 0 && !$form_state
    ->isRebuilding() && !$items
    ->getEntity()
    ->isNew()) {
    $field_name = $this->fieldDefinition
      ->getName();
    $cardinality = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getCardinality();
    $parents = $form['#parents'];
    if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
      $field_state = static::getWidgetState($parents, $field_name, $form_state);
      $field_state['items_count']--;
      static::setWidgetState($parents, $field_name, $form_state, $field_state);
    }
  }

  // Adjust wrapper identifiers as they are shared between parents and
  // children in nested field collections.
  $form['#wrapper_id'] = Html::getUniqueID($items
    ->getName());
  $elements = parent::formMultipleElements($items, $form, $form_state);
  $elements['#prefix'] = '<div id="' . $form['#wrapper_id'] . '">';
  $elements['#suffix'] = '</div>';
  $elements['add_more']['#ajax']['wrapper'] = $form['#wrapper_id'];
  return $elements;
}