You are here

public function EntityReferenceLayoutWidget::newItemSubmit in Entity Reference with Layout 8

Form submit handler - adds a new item and opens its edit form.

Parameters

array $form: The form array.

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

File

src/Plugin/Field/FieldWidget/EntityReferenceLayoutWidget.php, line 991

Class

EntityReferenceLayoutWidget
Entity Reference with Layout field widget.

Namespace

Drupal\entity_reference_layout\Plugin\Field\FieldWidget

Code

public function newItemSubmit(array $form, FormStateInterface $form_state) {
  $element = $form_state
    ->getTriggeringElement();
  $parents = $element['#element_parents'];
  $widget_state = static::getWidgetState($parents, $this->fieldName, $form_state);
  if (!empty($element['#bundle_id'])) {
    $bundle_id = $element['#bundle_id'];
  }
  else {
    $element_parents = $element['#parents'];
    array_splice($element_parents, -1, 1, 'type');
    $bundle_id = $form_state
      ->getValue($element_parents);
  }
  try {
    $entity_type = $this->entityTypeManager
      ->getDefinition('paragraph');
    $bundle_key = $entity_type
      ->getKey('bundle');
    $paragraphs_entity = $this->entityTypeManager
      ->getStorage('paragraph')
      ->create([
      $bundle_key => $bundle_id,
    ]);
    $paragraphs_entity
      ->setParentEntity($element['#host'], $this->fieldDefinition
      ->getName());
    $path = array_merge($parents, [
      $this->fieldDefinition
        ->getName(),
      'add_more',
      'actions',
    ]);
    $new_region = $form_state
      ->getValue(array_merge($path, [
      '_region',
    ]));
    $parent_weight = intval($form_state
      ->getValue(array_merge($path, [
      '_parent_weight',
    ])));
    $widget_state['items'][] = [
      'entity' => $paragraphs_entity,
      'is_new' => TRUE,
      'new_region' => $new_region,
      'parent_weight' => $parent_weight,
    ];
    $widget_state['open_form'] = $widget_state['items_count'];
    $widget_state['items_count']++;
    static::setWidgetState($parents, $this->fieldName, $form_state, $widget_state);
    $form_state
      ->setRebuild();
  } catch (\Exception $e) {
    watchdog_exception('Erl, new Item Submit', $e);
  }
}