1

I need to add some JavaScript to forms within my Omega 4 theme. My code right now is:

function mytheme_preprocess_form(&$vars) {
    $vars['element']['#attached']['js'][] = 'path/to/myjs';
}

This isn't working, but it seems like it should. I need to do this from my theme. I don't want to use drupal_add_js(), since that's being deprecated.

0

2 Answers 2

2

You cannot do what you want to do in the form preprocessor.

Try using hook_form_alter() instead.

Keep reading for more information on why your current code doesn't work.

If you look at drupal_render() you can see that it runs this to theme the element:

if (isset($elements['#theme'])) {
  $elements['#children'] = theme($elements['#theme'], $elements);
}

This call to theme() is pretty much where your preprocess code code is running.

The output of that theme function (theme_form() outputs a string of form markup) is then going into $elements['#children'].

Then further down in drupal_render() it does this:

if (!empty($elements['#attached'])) {
  drupal_process_attached($elements);
}

But the #attached code you added never ended up back in the $elements of the drupal_render() function though so nothing happened.

3
  • I can't do it (must do it in a theme for this project) in a module, unfortunately. I figured if I could call drupal_add_js() in my preprocess fx, then I could use #attached somehow. I guess I'll use drupal_add_js(), and just comment that I know I shouldn't use it, but hopefully Drupal 8 will let us do this in the theme with #attached.
    – vintorg
    Commented Nov 27, 2014 at 11:05
  • I'm now wondering if I can do this in an Omega theme function...
    – vintorg
    Commented Nov 27, 2014 at 11:16
  • @vintorg you can use a form alter in template.php (though it should only do themey things)
    – Andy
    Commented Nov 27, 2014 at 11:22
1

You can specify it in the .info file of your theme using scripts[] = 'path/to/myjs'

1
  • 2
    Yes, but I don't want to include this JS on every page.
    – vintorg
    Commented Nov 27, 2014 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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