0

Drupal 6. What is the proper way to execute drupal_add_js only when specific content_type is being created?

I have some jQuery code that needs to execute only to control some form elements in a specific content_type creation.

3

you need to write a simple module where you hook into the page you need and add drupal_add_js()

e.g. when you create a content type the form node_type_form is being called. so you have to hook into the form with

/**
 * implimentation of hook_form_alter()
 */
yourmodulename_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
}

I asume you need to add a JS to a content_type being viewed. in this case you will need to use hook_view() :

/**
 * implimentation of hook_view()
 */
yourmodulename_view($node) {
    if ($node->type == "your_type") {
        drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
    }
}

Update:

of course you can modify your template.php in the theme directory as well. remember that the theme for administration is different than the site theme by default. be aware which template.php file you are changing.

  • Thank you! Does the module need to have the same name as the content type? – djdy Nov 17 '11 at 18:37
  • +1 anonym-developer: what if it's added directly to the node-type.tpl.php file using drupal_add_js? would that be a wrong way of implementing it? – zarsiwala Nov 17 '11 at 22:40
  • @djdy: no, name it like you want and place in the sites/all/modules/_custom folder. I always have a mysettings module to set those things. – anonym-developer Nov 17 '11 at 22:59
  • @zarsiwala, its not the right way. you can put it in the template.php, probably the easier way, but never in the template file. image what happens if you list 5 different nodes in a view: your JS snipped/file will be parsed 5 times because the node.tpl.php is being parsed 5 times. – anonym-developer Nov 17 '11 at 23:02
  • @anonym-developer oh okay, thanks so much. I always wondered about this. – zarsiwala Nov 17 '11 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.