1

I created a custom form and I use a js library on it. I attached my JS in my template file but in a first time, I tried to attach it directly on my form with

$form['#attached']['library'][] = "mymodule/mylibrary" 

like in D7 but it doesn't work.

I found none references to attach library directly to a form and no references to the "#attached" property so I suppose it has been remove.

My library works fine in the twig template file.

But in the case I don't used a custom template or I use various templates for various cases, can I attach my library directly to my form without pass by a hook function or must I pass necessary by the template file, a hook_preprocess or a hook_page_attachment?

  • 1
    It hasn’t been removed (or even changed for a number of years) - #attached is valid on any render array, of which a form is one type, so documenting it specifically for forms isn’t necessary. I use it liberally without issue, keep plugging away you’ll get there eventually. Or if you need specific help, add some specifics to the question (code, libraries file, errors from the logs, etc) – Clive Nov 2 '17 at 19:47
  • Interesting. My library had never load when I add in the formBuild. No error in the console, no error in the syslog, the library was simply not load even if it was present in the form. When I added it in the template file, it worked. – Claire D Nov 2 '17 at 20:05
1

Like explain by Clive, add libraries directly in the form via '#attached' parameter works. The mistake in my case was to don't send my form properly to my template file. See Send a form to twig template

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.