Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 PST on 31 March 2024, to get $100 off your ticket.
I have a project which had drupal_add_js
calls in hook_init
. Coder properly produced warnings like below:
"Do not use drupal_add_js() in hook_init(), move it to your page/form callback or use hook_page_build() instead"
When the calls were moved to hook_page_build(), the following conflicting message appears for the same calls:
"Do not use drupal_add_js() in hook_page_build(), use #attached on the $page render array instead"
It seems like hook_page_build() usage shouldn't throw the warning. Maybe INFO?
Anyway, I wanted to raise this in case others can provide additional guidance.
Comment | File | Size | Author |
---|---|---|---|
#3 | updated-warning-text-2817537-3.patch | 1.47 KB | shrop |
Comments
Comment #2
klausiThis is expected behavior for hook_page_build(). You should use #attached whenever you have a render array, which you do in hook_page_build().
We could improve the warning message to say "Do not use drupal_add_js() in hook_init(), use #attached for JS in your page/form callback or in hook_page_build() instead"
Comment #3
shrop CreditAttribution: shrop at Mediacurrent commented@klausi,
Thank you for the details. I understand now on using #attached in hook_page_build(). That makes sense and I have applied the suggestion to my current related work!
I have attached a patch to this comment which may help clarify similar warnings for others. Please review and let me know if the text changes work. I have included mention if
drupal_add_css()
is used, since I think it also applies.drupal_add_css()
ordrupal_add_js()
inhook_init()
: "Do not use %s() in hook_init(), use #attached for CSS and JS in your page/form callback or in hook_page_build() instead"drupal_add_css()
ordrupal_add_js()
inhook_page_build():
"Do not use %s() in hook_page_build(), use #attached for CSS and JS instead"Comment #4
DamienMcKennaComment #5
DamienMcKennaShould the sentences have periods at the end?
Comment #6
DamienMcKennaComment #7
shrop CreditAttribution: shrop at Mediacurrent commentedI added periods at first and then did a look at the codebase and it looks like they are not added to other warnings. Glad to add them if we should start moving Coder to have proper punctuation. It definitely bothers me without them. :)
Comment #9
klausiImproved the second message a bit and committed it. Thanks!
Comment #10
shrop CreditAttribution: shrop at Mediacurrent commentedAwesome! Thank you!