You are here

public function ModalForm::ajaxSubmitForm in Editor Notes 8

Implements the submit handler for the modal dialog AJAX call.

Parameters

array $form: Render array representing from.

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

Return value

\Drupal\Core\Ajax\AjaxResponse Array of AJAX commands to execute on submit of the modal form.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/Form/ModalForm.php, line 250

Class

ModalForm
Implements the ModalForm form controller.

Namespace

Drupal\editor_note\Form

Code

public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) {

  // We begin building a new ajax reponse.
  $response = new AjaxResponse();

  // If the user submitted the form and there are errors, show them the
  // input dialog again with error messages. Since the title element is
  // required, the empty string wont't validate and there will be an error.
  if ($form_state
    ->getErrors()) {

    // If there are errors, we can show the form again with the errors in
    // the status_messages section.
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response
      ->addCommand(new OpenModalDialogCommand($this
      ->t('Errors'), $form, static::getDataDialogOptions()));
  }
  else {

    // We don't want any messages that were added by submitForm().
    $this->messenger
      ->deleteAll();
    $editor_note = $this
      ->getEditorNoteEntity($form_state);

    // This will be the contents for the modal dialog.
    $content = [
      '#type' => 'item',
      '#markup' => $this
        ->t('Note has been updated and saved.'),
    ];

    // Add the OpenModalDialogCommand to the response. This will cause Drupal
    // AJAX to show the modal dialog. The user can click the little X to close
    // the dialog.
    $response
      ->addCommand(new OpenModalDialogCommand($this
      ->t('Update selected item'), $content, static::getDataDialogOptions()));

    // Refresh editor note table.
    $replace_command = $this->editorNoteHelper
      ->getWidgetAjaxReplaceCommand($editor_note);
    $response
      ->addCommand($replace_command);
  }

  // Finally return our response.
  return $response;
}