1

I'm having an AJAX form, which on submit fires a callback function where I want to attach my library.

Here's the submit button:

$form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => 'Submit',
    '#button_type' => 'primary',
    '#name' => 'calculate',
    '#submit' => ['::submitForm'],
    '#ajax' => [
      'callback' => [$this, 'submitFormCallback'],
      'wrapper' => 'my-form-id',
    ],
];

When the submitFormCallback is called I attach my library using AjaxResponse and its addAttachments like this:

$ajax_response->addAttachments([
  'library' => ['my_module/library_name']
]);

The problem is when the AJAX is completed the whole page's layout is destroyed. When I do NOT attach the library to AJAX response everything seems to work fine. (I've already tried to empty my JS files in my_module/library_name so the javascript won't affect any DOM elements, but the result is the same.

Is there any problem with the way I attach the library to AjaxResponse that may cause the broken layout?

1 Answer 1

1

Is there any problem with the way I attach the library to AjaxResponse that may cause the broken layout?

I guess so. This is how core does it when its an AJAX response, it attaches it to the form like this:

$form['#attached']['library'][] = 'my_module/library_name';
$ajax_response->setAttachments($form['#attached']);
5
  • thanks, your solution seems to work. The other issue was that CSS styles in library were breaking layout of page's CSS styles too. Nov 10, 2020 at 7:10
  • 1
    There is no difference between both code examples by only showing these lines. The question is why you need to attach the libraries this way. You need this only if you have executed renderRoot() on $form bubbling up the libraries to the top level of $form. Instead of letting the Ajax layer doing it automatically by passing the unrendered $form.
    – 4uk4
    Nov 10, 2020 at 8:23
  • I created a form, where on submit event is my custom JS library attached, which displays OpenLayer map with points and routes. The problem was that I only needed to attach the library on form submit event not before form's submission. Nov 10, 2020 at 8:32
  • The form submit process runs before the Ajax callback. You just named it and then used it this way.
    – 4uk4
    Nov 10, 2020 at 8:53
  • When you rebuild the form after submit add the elements you want to display including the necessary libraries, independently from how you plan to deliver the rebuilt form.
    – 4uk4
    Nov 10, 2020 at 10:05

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.