3

I'd like to load a javascript file only if a specific field has data. Can this be done with a preprocess function in template.php? Something like:

if this field is not empty
  add the js to the page footer
else do nothing

Is there a more efficient way?

2

If a field within a specific content type has some content, load some javascript, if there's nothing in the field, do nothing.

function THEME_NAME_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "CONTENT_TYPE") {
    if(!empty($variables['node']->FIELD_NAME)) {
      drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . 'PATH-TO-JS.js', array('type' => 'file', 'scope' => 'footer'));

    }
  }
}
1
  • something wrong happened I guess,please add your snippet again – arpitr Oct 2 '13 at 18:48
1

yes, doable at your template.php file

not the exact code but should be pretty close.

function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your_content_type") {
     dpm($variables['node']); // to check debugg inside your node(devel module needed)
     if($variables['node']->yourfieldname != "") {
      drupal_add_js(drupal_get_path('theme', 'mytheme') .'/mytheme.js', 'file');
    }
  }
}
4
  • A slight variation of this worked – Brian P Oct 2 '13 at 18:42
  • if the variation is not specific, please share would be help for others searching for something same :) – arpitr Oct 2 '13 at 18:45
  • New to this site, answered my own question with the variation. Thanks for your help. – Brian P Oct 2 '13 at 18:48
  • please add the snippet one more time, something wrong happened while editing :) – arpitr Oct 2 '13 at 18:50
1

I'm assuming that it's a node page, you can do it in your template.php as follows:

function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $content = $variables['content'];
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    if ($content['YOUR_FIELD']) {
      $js_path = drupal_get_path('theme', 'YOURTHEME') . '/yourjs.js';
      drupal_add_js($js_path, array('scope' => 'footer'));
    }
  }
}

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.