2

I'm using hook_form_alter. I'm having a weird situation where attaching my library works only if I do what I would think is incorrect:

$form['#attached']['library'] = array('somemodule/somelibrary');

But not if I do this:

$form['#attached']['library'][] = array('somemodule/somelibrary');

What could cause a thing like this? I debugged to see what was happening in the FormBuilder, but it seems like the library is added either way. It's not removed by any other module or anything.

  • 1
    Note that you have to add the module / theme name before the library name: core/drupal, foo_module/bar_library – Eyal Feb 14 '17 at 18:27
  • Yes, I just changed the library's name for the example, I'll update the question so it follows that format. – RaisinBranCrunch Feb 14 '17 at 18:30
5

Those two statements are not equal.

$form['#attached']['library'] = array('somelibrary');

Resets the library array to only contain "somelibrary". This would remove anyone else's library that may need to get loaded.

$form['#attached']['library'][] = 'somelibrary';

This adds "somelibrary" to the existing libraries array for inclusion. (this is correct)

$form['#attached']['library'][] = array('somelibrary');

This is the wrong structure.

For Drupal 8

$form['#attached']['library'][] = 'somemodule/somelibrary';

  • Plus, don't you need the format name/library? – Kevin Feb 14 '17 at 17:59
  • No, just the machine name. I think the key doesn't matter. – iLLin Feb 14 '17 at 18:08
  • Correct answer, but yes, you definitely need module/library-name. – Berdir Feb 14 '17 at 18:26
  • Is that a drupal 8 update? – iLLin Feb 14 '17 at 18:28

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.