You are here

public static function FormAlter::ajaxFormEntityFormSubmit in Ajax form entity 8

Ajax form submit, rebuild the form.

Parameters

array $form:

\Drupal\Core\Form\FormStateInterface $form_state:

File

src/Form/FormAlter.php, line 26

Class

FormAlter
Class FormAlter.

Namespace

Drupal\ajax_form_entity\Form

Code

public static function ajaxFormEntityFormSubmit(array $form, FormStateInterface $form_state) {
  $build_info = $form_state
    ->getBuildInfo();
  if (empty($build_info['callback_object'])) {
    return;
  }

  /* @var $callback \Drupal\Core\Entity\EntityForm */
  $callback =& $build_info['callback_object'];

  // Get the entity.
  $entity = $callback
    ->getEntity();
  $entity_type = $entity
    ->getEntityTypeId();
  $bundle = $entity
    ->bundle();

  // Replace the form entity with an empty instance if needed.
  $configurations = $form_state
    ->getValue('ajax_form_entity');
  if ($configurations['reload'] != 'reload_entity') {

    // @todo : injection
    $new_entity = \Drupal::entityTypeManager()
      ->getStorage($entity_type)
      ->create([
      'type' => $bundle,
    ]);
    $callback
      ->setEntity($new_entity);
  }

  // Clear user input.
  $input = $form_state
    ->getUserInput();

  // We should not clear the system items from the user input.
  $clean_keys = $form_state
    ->getCleanValueKeys();
  $clean_keys[] = 'ajax_page_state';
  foreach ($input as $key => $item) {
    if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
      unset($input[$key]);
    }
  }

  // Store new entity for display in the AJAX callback.
  $input['entity'] = $entity;
  $form_state
    ->setUserInput($input);

  // Rebuild the form state values.
  $form_state
    ->setRebuild();
  $form_state
    ->setStorage([]);
}