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.
Drupal.settings.mymodule.test
notDrupal.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');
.