drupal_add_js not work in form validation failed

Modifying a form in Drupal may be a little challenging sometimes, so here is a small tip for those working with form_alter or forms in general.

There is an optional form element called $form['#after_build'] it takes an array of functions to call (similar to $form['#submit']). What this does is it runs after the form or element is built for display.

When is it a good time to use this? The answer is most of the times when a modification to CCK fields should be done, this is to ensure that the entire form and all the other form alterations have already occurred from all modules. Lets say you want to form_alter an attribute or value of a field in a form, but it is altered in another contributed module already. Depending on the weight of the modules your form_alter may get overwritten so the solution is to run it after the form has been built. At this point you want to make sure it runs the alterations in the contributed modules first before your change occurs, then it is best to use #after_build.

I have also encountered times when I want to load a js or css file whenever the form is rendered. If I place it into a form_alter they are loaded fine, but if I submit the form and the form does not pass validation the page is reloaded without the js or css file added. Placing the drupal_add_js or drupal_add_css into the after_build solves these issues.

Here is some basic code for reference, which goes into one of your custom modules.

function yourmodulename_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'thisformid'){
$form['field']['#prefix'] = 'This text gets overwritten by the after build';
$form['#after_build'][] = 'yourmodulename_after_build'; //Calls function
//drupal_add_css('hello.css'); This line does not work when validation fails
}
}

function yourmodulename_after_build($form, &$form_state) {
$form['field']['#prefix'] = 'This text will rule them all!';
drupal_add_css('hello.css'); //This line works even after validation fails.
return $form;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

WordPress.com.

Up ↑

%d bloggers like this: