Form Alter and #after_build
Hey,
We have all faced situations in a drupal site where we have to insert js to controll form behaviours.
The common method that i had followed till now is to either
* Add a drupal_add_js in the form function or
* use a hook form alter to inset js using the same drupal_add_js
But if the the form fails validations then the js files are not included. This is because the Drupal caches the forms. And when there is a validation error it just pulls the forms from the cache.
I found my alternative here
http://drupal.org/node/908910#comment-3485270
Drupal forms have a parameter called #after_build
This is mainly used to alter fields after creating their displays.
But the callbacks given here will be trigerred even when the form is reproduced from cache!
That solved my problem..
You can find more details about #after_build here





Comments
test (not verified)
Tue, 04/19/2011 - 12:38
Permalink
Added the drupal_add_js to
Added the drupal_add_js to the validation function itself.
function someform_validate_form($form, &$form_state)
{
drupal_add_js('some-js-code', 'inline', 'header');
}
naughty_david
Tue, 04/19/2011 - 18:49
Permalink
But Validate will be called
But Validate will be called only once the form is Submitted.
The actual js functions should be performed when the form is Show..!
This method requires you to add the js in the form and inside the validate function...
Deeps (not verified)
Mon, 11/07/2011 - 12:40
Permalink
How to identify which js
How to identify which js files need to add in validate_form function?
naughty_david
Tue, 11/08/2011 - 10:19
Permalink
Literally, None should be
Literally, None should be added
Validate functions are server side callbacks,
And they are executed on cached forms. Hence the js files wont be included on every submit.
But #after_build is called for each field on each rendering of the form, even while showing error messages. And drupal_add_js will only add a js file once, hence this effectively is the best way to add js to a form.
To do it the PRO way, try CTOOLS API :) I am in love with it now