drupal_add_js in hook_form_alter
skilip - October 16, 2008 - 20:08
| Project: | Drupal |
| Version: | 6.x-dev |
| Component: | forms system |
| Category: | support request |
| Priority: | normal |
| Assigned: | Unassigned |
| Status: | closed |
Jump to:
Description
If I add drupal_add_js in a form_alter I adds the scripts like it should when the form is in it's normal state. However, after a submition of the form, and the form did not pass the validation, the scripts aren't present any more.

#1
drupal_add_css() also doesn't function anymore after page refresh with validation errors
#2
This is my code:
<?php/**
* Implementation of hook_form_alter().
*/
function swfupload_form_alter(&$form, $form_state, $form_id) {
$path = drupal_get_path('module', 'swfupload');
drupal_add_css("$path/swfupload.css");
drupal_add_js("$path/swfupload.src.js");
}
?>
I've already tried to set the cache argument for drupal_add_js to FALSE, but no success.
#3
I found out if you add the identical lines to the _form_validate hook you can have your js and css load after a validation error.
<?php
/**
* Implementation of hook_form_alter().
*/
function swfupload_form_alter(&$form, $form_state, $form_id) {
$path = drupal_get_path('module', 'swfupload');
drupal_add_css("$path/swfupload.css");
drupal_add_js("$path/swfupload.src.js");
}
/**
* Implementation of hook_form_validate().
*/
function swfupload_form_validate(&$form, $form_state, $form_id) {
$path = drupal_get_path('module', 'swfupload');
drupal_add_css("$path/swfupload.css");
drupal_add_js("$path/swfupload.src.js");
}
?>
#4
This also happens in hook_form. If you create a node type via a module and use drupal_add_js in hook_form, the JavaScript code will to be included if the form doesn't pass validation.
#5
hook_form_alter() will not be called again if the *form* is cached for efficiency. Set the form to be non-cacheable to get hook_form_alter() called again. Or use the other creative ways mentioned here to add JS to forms being altered (you can also add it based on paths and other tricks in hook_init() and hook_help()).
#6
I've managed to solve this by adding a callback to '#after_build' in which the js and css files are added.
#7
The best way is to create a theme function and add CSS / JS files there. It makes little sense to use a #build_after callback for this.
#8
Thanks.