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

skilip - October 28, 2008 - 10:24
Priority:normal» critical
Status:postponed (maintainer needs more info)» active

drupal_add_css() also doesn't function anymore after page refresh with validation errors

#2

skilip - October 28, 2008 - 11:09
Project:API» Drupal
Version:HEAD» 6.x-dev
Component:Code» forms system

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

markDrupal - November 4, 2008 - 19:57

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

gains - November 22, 2008 - 02:02

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

Gábor Hojtsy - January 8, 2009 - 12:20
Category:bug report» support request
Priority:critical» normal
Status:active» closed

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

skilip - January 8, 2009 - 12:29

I've managed to solve this by adding a callback to '#after_build' in which the js and css files are added.

#7

Damien Tournoud - January 8, 2009 - 12:31

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

kenorb - May 21, 2009 - 11:35

Thanks.

 
 

Drupal is a registered trademark of Dries Buytaert.