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.

CommentFileSizeAuthor
#3 updated-warning-text-2817537-3.patch1.47 KBshrop
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

shrop created an issue. See original summary.

klausi’s picture

This 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"

shrop’s picture

@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.

  • Message if a user attempts drupal_add_css() or drupal_add_js() in hook_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"
  • Message if a user attempts drupal_add_css() or drupal_add_js() in hook_page_build(): "Do not use %s() in hook_page_build(), use #attached for CSS and JS instead"
DamienMcKenna’s picture

Status: Active » Needs review
DamienMcKenna’s picture

Should the sentences have periods at the end?

DamienMcKenna’s picture

Version: 8.x-2.8 » 8.x-2.x-dev
shrop’s picture

I 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. :)

  • klausi committed 05f20ea on 8.x-2.x authored by shrop
    fix(HookInitCssSniff): Improve warning message wording (#2817537 by...
klausi’s picture

Status: Needs review » Fixed

Improved the second message a bit and committed it. Thanks!

shrop’s picture

Awesome! Thank you!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.