Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
googletorp Avatar asked Apr 06 '10 11:04

googletorp


1 Answers

Trying some different hacks, I found a quite simple solution to this problem, create a theme function for the form and add the js there. That would look something like this:

function theme_content_type_node_form($form) {
  drupal_add_js(...);
  return theme('node_form', $form);
}

This just calls the default theme function for the node add form after adding the js. As the theme function is called even the form is cached, this works nicely. You also need to implement hook_theme to make this work.

Update for Drupal 7.

Drupal 7 makes this a lot easier as it is possible to do

$form['#attached']['js'][] = 'path_to_js_file';

An example of using this could be:

$form['#attached']['js'][] = drupal_get_path('module', 'foo') . '/js/foo.form.js';
like image 136
googletorp Avatar answered Oct 02 '22 10:10

googletorp