tags:

views:

30

answers:

2

Hi,

In a custom module, I have the following (to add javascript to a particular form):

function mymodule_form_mynode_node_form_alter(&$form, $form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js', 'module');
}

This function does get called the form is first loaded (i.e. browse to http://myserver.com/node/add/mynode) however this php function does not get called when the same form is reloaded after the form has been invalidated (i.e. missed a required field after clicking 'Submit' or 'Preview').

What do I need to do to have the javascript file added after 'Submit' or 'Preview' is clicked?

Thanks,

John

+1  A: 

To solve your problem, you'll need to create a theme function for the form where you render the form and add the js file.

googletorp
A: 

You form alter is only called when the form is build. As forms are cached between request, the same and already build form is used on submit and preview.

You need to unsure that your code is called each time the form is rendered. As pointed out by googletorp, one way to do it is to use a custom form rendering function. You can also do it by attaching a post or pre-rendering function to your form. Actually, the custom, pre or post rendering function doesn't need to be for the form itself and can be used on any form element. Preferably the one which behavior is altered by the JavaScript.

mongolito404