Below is the code I have tried in D7. I am doing it while node (Node No 1/Node No 2) is being created or, edited. So, changes will get reflected in node view as well. (There can be other approaches like using 'Hierarchical Select'). Here is the code :
/**
* Implements hook_node_validate()
* @param $node
* @param $form
* @param $form_state
* @return unknown_type
*/
function common_operations_node_validate($node, $form, &$form_state) {
if ($node->type == 'node_no') { // If node is of type 'node_no'
if (isset($node->field_region_and_state[$node->language])) {
if (count($node->field_region_and_state[$node->language]) > 1) { // Multiple terms are associated
foreach ($node->field_region_and_state[$node->language] as $key => $val) {
$vid = 0; $children = array(); // Variable Declaration & Initialization
// Helper function call to get 'VID' for a 'TID'
$vid = common_operations_get_term_vid($val['tid']);
// Get all children for a 'TID'
$children = taxonomy_get_children($val['tid'], $vid);
if (count($children)) { // Restricting user to select only last level term in the hierarchy
form_set_error('field_region_and_state', 'Some Message.');
}
}
}
else { // Only a single term is associated
$vid = 0; $children = array(); // Variable Declaration & Initialization
// Helper function call to get 'VID' for a 'TID'
$vid = common_operations_get_term_vid($node->field_region_and_state[$node->language][0]['tid']);
// Get all children for a 'TID'
$children = taxonomy_get_children($node->field_region_and_state[$node->language][0]['tid'], $vid);
if (count($children)) { // Restricting user to select only last level term in the hierarchy
form_set_error('field_region_and_state', 'Some Message.');
}
}
}
}
}
/**
* Helper function to get 'VID' for a 'TID'
* @param $tid
* @return unknown_type
*/
function common_operations_get_term_vid($tid) {
$vid = 0; // Variable Declaration & Initialization
$query = db_select ('taxonomy_term_data', 'ttd' );
$query->fields ('ttd', array ('vid'));
$query->condition ('ttd.tid', $tid, '=');
$vid = $query->execute ()->fetchField ();
return $vid;
}
1) 'common_operations' is name of module
2) 'node_no' is type of node
3) Structure -
Europe
England
London
Node No 1
France
Paris
Node No 2
Here, 'Node No 1' is a node of type 'node_no' associated with immediate parent in the hierarchy 'London'
'Node No 2' is a node of type 'node_no' associated with immediate parent in the hierarchy 'Paris'
4) field_region_and_state is the 'Term Reference' field in content of type 'node_no'
So, when you try to create/edit the node you can associate the node only with the last level of the hierarchy.
Hope it helps.