Drupal - Right way to add JS and CSS to node/edit and other forms

If you wish to add JS and CSS to the node edit page in particular (or any form in general), the best and the right place to do so is the hook_form_alter() and the property you should be using is #after_build.

This comment on DO tells you exactly what to do - http://drupal.org/node/1253520#comment-4881588

Hope this helps :-)


You should use the #attached property to ensure that JS/CSS always get's loaded properly together with another render element.


I felt these answers & comments desperately needed example code, particularly those of @AyeshK and @Letharion. This is too long for a comment, so please forgive the answer. If it's useful to you, please up-vote either Sumeet or Letharion's answer. Also, the following example obviously adds CSS, but would be nearly identical for adding javascript.

Using @Sumeet's answer, but using the #attached property instead of drupal_add_css, looks like this:

/* Implements hook_form_FORM_ID_alter() */
function MY_MODULE_form_MY_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'MY_MODULE_some_function_name_after_build';
}

function MY_MODULE_some_function_name_after_build($form, &$form_state) {
  $style_path = drupal_get_path('module','MY_MODULE') . '/css/my_css.css';
  // drupal_add_css('file', $style_path);
  $form['#attached']['css'][] = $style_path;
  return $form;
}

Finally, the deprecation of drupal_add_css can be found in this post. That may be news to many for whom drupal_add_xxx was working just fine, as it was for me.

Tags:

Theming

Hooks