You are here

public static function WidgetSubmit::doSubmit in Inline Entity Form 8

Submits the widget elements, saving and deleted entities where needed.

Parameters

array $form: The form.

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

File

src/WidgetSubmit.php, line 40

Class

WidgetSubmit
Performs widget submission.

Namespace

Drupal\inline_entity_form

Code

public static function doSubmit(array $form, FormStateInterface $form_state) {
  $referenceUpgrader = new ReferenceUpgrader();
  $widget_states =& $form_state
    ->get('inline_entity_form');

  // Widget states can be in an arbitrary order depending on user's form
  // interaction. We sort them lexicographically in reverse order to get inner
  // forms before outer forms, to ensure inside-out saving of entities.
  // @see \Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormBase::makeIefId
  krsort($widget_states, SORT_STRING);
  foreach ($widget_states as $ief_id => &$widget_state) {
    $widget_state += [
      'entities' => [],
      'delete' => [],
    ];
    foreach ($widget_state['entities'] as $delta => &$entity_item) {
      if (!empty($entity_item['entity']) && !empty($entity_item['needs_save'])) {

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        $entity = $entity_item['entity'];
        $handler = InlineEntityForm::getInlineFormHandler($entity
          ->getEntityTypeId());
        $referenceUpgrader
          ->upgradeEntityReferences($entity);
        $handler
          ->save($entity);
        $referenceUpgrader
          ->registerEntity($entity);
        $entity_item['needs_save'] = FALSE;
      }
    }

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entities */
    foreach ($widget_state['delete'] as $entity) {
      $entity
        ->delete();
    }
    unset($widget_state['delete']);
  }
}