'Adding js to a drupal node form

In Drupal you can create your own nodetype in a custom module. Doing this you get to create your own form which is all very nice.

However if you want to add js the form things get a bit more tricky. If you add the js in the form, the js will only be added form the form when it is loaded. If the user would post the form with validation errors, the form function is not run again and thus the js is not added. Normally you would just create a menu callback and add the js there, but for the node add form, this wont be a possible solution.

So what is the best solution for adding js in a node add form, to keep it persistant when the form doesn't validate?



Solution 1:[1]

I posted a patch to the Smilies module that fixes this problem: Smilies are not selectable when resubmitting a page

The patch adds a hook_nodeapi() function to check if the node operation is "verify" and if it is, it checks if the node is supposed to have smileys and if so calls the function to add the smileys.js javascript file that creates the selection form.

You should just need to do the same in your case. This will require you write a very simple module that implements the hook_nodeapi function and checks for updates in the same way the patched Smileys module does.

Solution 2:[2]

You can user hook_nodeapi with case prepare:

Example:

/**
 * Implementation of hook_nodeapi
 */

function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch($op) {     
    case 'prepare':
      $module_path = drupal_get_path('module' , 'mymodulename'); 
      drupal_add_js($module_path."/myscript.js");
      break; 
  }
}

Now you can add your javascript code in your module folder e.g. myscript.js.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alxp
Solution 2 kenorb