Hello all!

I'm writing some custom JS that needs to be added to the node form add/edit page for a specific content type. Looking thru what operations I could use for hook_nodeapi, I thought 'prepare' might work. However, it seems that it doesn't get invoked if a form validation error occurs.

I came across this stack overflow post regarding the issue, which suggests overriding the template function for the form and adding in my JS. Is that the best solution?
http://stackoverflow.com/questions/2584405/adding-js-to-a-drupal-node-form

Thank you

Brian

Comments

Web Assistant’s picture

I might be being a bit thick, but can't you just add the JS via hook_form_alter()?

bkosborne’s picture

I think the forms alters and only called when the form is rebuilt - which doesn't happen in form validations and a few other instances i believe.

zbricoleur’s picture

Use hook_form_alter to add an afterbuild function. That will add the js even on validation errors.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_form':
      $form['#after_build'][] = 'mymodule_after_build';
      break;
  }
}

function mymodule_after_build($form, &$form_state) {
  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js ("$path/mymodule.js");
  return $form;
}
lmeurs’s picture

Works for me, exactly what I was looking for. Thank you!

Laurens Meurs
wiedes.nl

fpap’s picture

Great! It works on Drupal 7 too.

Thank you.

Coufu’s picture

My JS would add in hook_form_alter(), but stopped adding on validation. zbricoleur's solution worked for me. Thank you.