function ModalForm::ajaxSubmitForm

Same name in other branches
  1. 3.x modules/form_api_example/src/Form/ModalForm.php \Drupal\form_api_example\Form\ModalForm::ajaxSubmitForm()

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.

File

modules/form_api_example/src/Form/ModalForm.php, line 156

Class

ModalForm
Implements the ModalForm form controller.

Namespace

Drupal\form_api_example\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();
        // We use FormattableMarkup to handle sanitizing the input.
        // @todo There's probably a better way to do this.
        $title = new FormattableMarkup(':title', [
            ':title' => $form_state->getValue('title'),
        ]);
        // This will be the contents for the modal dialog.
        $content = [
            '#type' => 'item',
            '#markup' => $this->t("Your specified title of '%title' appears in this modal dialog.", [
                '%title' => $title,
            ]),
        ];
        // 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($title, $content, static::getDataDialogOptions()));
    }
    // Finally return our response.
    return $response;
}