I have a user form mode (like node view mode except for forms) opened in a modal. When this form is submitted the user entity is updated and the modal is closed. This works fine. I now want to extend this where the user is updated, the modal is closed and a 2nd modal is opened with another custom form.

In my original AJAX response call I have simply added this:

  // Get the modal form using the form builder.
  $accept_form = \Drupal::formBuilder()->getForm('Drupal\sia_mpep\Form\SendPolicyEndorsementForm');

  // Add an AJAX command to open a modal dialog with the form as the content.
  $response->addCommand(new OpenModalDialogCommand(t('Send policy endorsement form'), $accept_form, ['width' => '1000']));

The custom form is fairly simple and has this at the end:

$form['actions'] = ['#type' => 'actions'];
$form['actions']['send'] = [
  '#type' => 'submit',
  '#value' => $this->t('Send'),
  '#attributes' => [
    'class' => [
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],

$form['#attached']['library'][] = 'core/drupal.dialog.ajax';

return $form;

but when I submit the 2nd form; neither the submitForm nor the submitModalFormAjax methods are hit. I noticed that the action attribute in the form tag is still set to the original user form edit (modal #1) and I read that I need to define a route to my new form and set #action to the new route:

$form['#action'] = \Drupal\Core\Url::fromRoute('route_to_my_form')->toString();

This does set the action in my form tag to point to that path; but still doesn't submit to my submitForm() handler. It also has the downside of now having a page which shows my form - which I don't need.

When I submit the ajax spinner spins for a while and then I get an AJAX error in console which looks as though the form may still be submitting to the user form handler.

I am guessing there must be something simple missing here.


1 Answer 1


This is a gotcha of AJAX forms.

When you load an AJAX form via AJAX it loses its AJAX functionality.

In order to keep it working, for the form that is getting loaded via ajax, you need to add a url and options keys to #ajax

  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'url' => \Drupal\Core\Url::fromRoute('your.form.route.name'),
    'options' => [
      'query' => [
        \Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
  • Excellent. Thank you.
    – liquidcms
    Commented Aug 11, 2023 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.