3

I am working with a feature where a newsletter subscription form (Webform with ajax submission and confirmation type is inline) should appear in a node. The node would be showing as a popup and the contents of popup is being loaded using ajax. When the node is tested in it's own node page the submission is working fine but not in the popup.It is redirecting to another page. Inspecting the two cases, i found that the webform while being loaded in popup, lacks event handler that should refer to form submission.

In the controller where webform being loaded into the popup block, something like this is tried:

  $webform = $this->entityTypeManager->getStorage('webform')->load($formId);
  $view_builder = $this->entityTypeManager->getViewBuilder('webform');
  $build = $view_builder->view($webform);

Where $formId is the id of the webform and entityTypeManager is an instance of Drupal\Core\Entity\EntityTypeManagerInterface. Later this $build is being saved as the webform attribute of popup class and later being rendered. The fields of the webform appears to be loaded correctly but not the event of submission form. Any suggestion for solving the issue?

3

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

/*
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // I created a webform called "test"
  if ($form_id == 'webform_submission_test_add_form') {
    $webform_id = 'test';
    $form['actions']['submit']['#ajax']['url'] = \Drupal\Core\Url::fromRoute('entity.webform.canonical', ['webform' => $webform_id]);
    $form['actions']['submit']['#ajax']['options'] = [
      'query' => [
        Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ];
  }

}

Side note: this loss of AJAX issue doesn't occur with the HTML way of opening dialog boxes

<a class="use-ajax" 
   data-dialog-options="{&quot;width&quot;:600}" 
   data-dialog-type="modal" 
   href="/form/test">
   Should load Test webform in a Modal
</a>

because it has the URL of the form and knows its an AJAX request from the class name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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