1

I have tried to do this a couple of different ways, but I will just include the latest.

My task is to build a module that will get the STRING value of a taxonomy term by the machine name of the field when the page is rendered, and pass that STRING value to a javascript function to output data in a block.

Most recently, I have tried adding the code to the template.php file in the preprocess_html, page, node and process_html:

*The field is called 'field_test'

global $nid;
$node = node_load('12');
$test = $node->field_test['und'][0]['value'];
drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');

Error in processes was a call to undefined index. Error in page.tpl was a call to non object.

I also tried field_get_items:

$items = field_get_items('node', $node, 'field_test');
$first_item = array_shift($items);
$test = $first_item['value'];

In the node.tpl file, I tried adding this code:

<?php
  $test = $node->field_test['und'][0]['value'];
  drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');
?>

No errors, but Drupal.settings.test returns undefined in the browser console.

I'll admit I am still new to the Drupal API. In addition to the correct code, I may also lack an understanding of the order in which Drupal components are loaded, and specifically where the code should be placed.

I would really appreciate any help you can provide.

3
  • Could you include the Drupal version you are using in the question? Commented Oct 5, 2017 at 20:18
  • It should be Drupal.settings.mymodule.test not Drupal.settings.test. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try $node = menu_get_object('node');.
    – Kevin
    Commented Oct 5, 2017 at 20:19
  • Updating to include Drupal version - thanks @neograph
    – lane
    Commented Oct 5, 2017 at 20:56

1 Answer 1

2

It should be Drupal.settings.mymodule.test not Drupal.settings.test. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try $node = menu_get_object('node');.

Example:

if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

In your console (like Google Chrome) you can type Drupal.settings to see the entire object, and you should see mymodule as a part of it. Within that you will find test with the term name as a value.

1
  • Killer. That did it. You rock!
    – lane
    Commented Oct 5, 2017 at 21:40

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.