You are here

public function EntityEmbedDialog::submitEmbedStep in Entity Embed 8

Form submission handler for the entity embedding step.

On success this will submit the command to save the embedded entity with the configured display settings to the WYSIWYG element, and then close the modal dialog. On form errors, this will rebuild the form and display the error messages.

Parameters

array $form: An associative array containing the structure of the form.

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

Return value

\Drupal\Core\Ajax\AjaxResponse The ajax response.

File

src/Form/EntityEmbedDialog.php, line 797

Class

EntityEmbedDialog
Provides a form to embed entities by specifying data attributes.

Namespace

Drupal\entity_embed\Form

Code

public function submitEmbedStep(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // Submit configuration form the selected Entity Embed Display plugin.
  $entity_element = $form_state
    ->getValue('attributes');
  $entity = $this
    ->loadEntityByAttributes($entity_element);
  $plugin_id = $entity_element['data-entity-embed-display'];
  $plugin_settings = !empty($entity_element['data-entity-embed-display-settings']) ? $entity_element['data-entity-embed-display-settings'] : [];
  $display = $this->entityEmbedDisplayManager
    ->createInstance($plugin_id, $plugin_settings);
  $display
    ->setContextValue('entity', $entity);
  $display
    ->setAttributes($entity_element);
  $display
    ->submitConfigurationForm($form, $form_state);
  $values = $form_state
    ->getValues();

  // Display errors in form, if any.
  if ($form_state
    ->hasAnyErrors()) {
    unset($form['#prefix'], $form['#suffix']);
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response
      ->addCommand(new HtmlCommand('#entity-embed-dialog-form', $form));
  }
  else {

    // Serialize entity embed settings to JSON string.
    if (!empty($values['attributes']['data-entity-embed-display-settings'])) {
      $values['attributes']['data-entity-embed-display-settings'] = Json::encode($values['attributes']['data-entity-embed-display-settings']);
    }

    // Filter out empty attributes.
    $values['attributes'] = array_filter($values['attributes'], function ($value) {
      return (bool) mb_strlen((string) $value);
    });

    // Allow other modules to alter the values before getting submitted to the
    // WYSIWYG.
    $this->moduleHandler
      ->alter('entity_embed_values', $values, $entity, $display);
    $response
      ->addCommand(new EditorDialogSave($values));
    $response
      ->addCommand(new CloseModalDialogCommand());
  }
  return $response;
}