You are here

public function FieldInheritanceAjaxForm::ajaxSubmit in Field Inheritance 8

Same name and namespace in other branches
  1. 2.0.x src/Form/FieldInheritanceAjaxForm.php \Drupal\field_inheritance\Form\FieldInheritanceAjaxForm::ajaxSubmit()

File

src/Form/FieldInheritanceAjaxForm.php, line 92

Class

FieldInheritanceAjaxForm
Provides an AJAX form for managing field inheritance entities.

Namespace

Drupal\field_inheritance\Form

Code

public function ajaxSubmit(array $form, FormStateInterface $form_state) {
  parent::save($form, $form_state);
  $response = new AjaxResponse();
  $response
    ->addCommand(new CloseModalDialogCommand());

  // Grab the values from the form.
  $form_values = $form_state
    ->getValues();

  // Build an empty entity using the destination entity type and bundle.
  $entity = $this->entityTypeManager
    ->getStorage($form_values['destination_entity_type'])
    ->create([
    'type' => $form_values['destination_entity_bundle'],
  ]);

  // Build the entity form for the created entity.
  $form = $this->entityFormBuilder
    ->getForm($entity, 'default');

  // Grab the field inheritance field for the specified entity and add it to
  // the parent form.
  $field = $form['field_inheritance']['fields']['field_inheritance_' . $form_values['id']];
  $response
    ->addCommand(new AppendCommand('#field-inheritance-ajax-container', $field));

  // Display the messages generated by the creation of the field inheritance.
  $message = [
    '#theme' => 'status_messages',
    '#message_list' => $this->messenger
      ->all(),
  ];

  // Prevent duplicate messages appearing.
  $this->messenger
    ->deleteAll();

  // Render the messages.
  $messages = $this->renderer
    ->render($message);
  $response
    ->addCommand(new HtmlCommand('#field-inheritance-ajax-message', $messages));
  $response
    ->addCommand(new ScrollTopCommand('#field-inheritance-ajax-message'));
  return $response;
}