4

I'm trying to load a form into a div using a javascript call. I can get the form in the div, but nothing works (autocomplete fields, wysiwyg fields, custom submit handler).

I know I must be missing something, but I can't figure out what it is.

What I have now to get the form:

$form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');
$renderable = [
   '#theme' => 'my_form',
   '#form' => $form,
];
$rendered = Drupal::service('renderer')->renderPlain($renderable);

$response = new AjaxResponse();
$response->setData($rendered);
return $response;

I've also tried renderRoot instead of renderPlain, but to no avail.

The twig file looks like this (very simple):

<div id="form-container">
    {% include 'header.html.twig' with {
        type : 'manual'
    } %}
    <div class="content">
        {{ form }}
    </div>
</div>

Any help will be greatly appreciated.

1 Answer 1

4

You have to add ajax commands to the ajax response, using the unrendered render array:

$response->addCommand(new ReplaceCommand('#form-container', $renderable));

BTW you can only return a Drupal ajax response if you have triggered an ajax request via ajax.js. Outside of form submits you usually do this by adding the class use-ajax to a link. For custom js code see How to Trigger Existing, Non-Form Ajax from JavaScript Event

2
  • Thanks, unfortunately this was not a route I could take, so now I have pre-loaded the form on the page (using twig) and display/hide the form when it is needed. Commented Sep 29, 2020 at 7:26
  • OK, you don't need Ajax if you can pre-load static content. But a lot of use cases are more dynamic.
    – 4uk4
    Commented Sep 29, 2020 at 7:41

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.