3

Is it possible at all to create a node template file based on a specific field value?

For example I already have a node template file called "node--video.tpl.php" for nodes of content type video. I would now like to add a checkbox field in that content type.

If the box is unchecked then it will use the above template.

If the box is checked then it will use a different template.

UPDATE: I added the following to my template file as Mohammed suggested, but I am not getting the changes.

function motg_preprocess_node(&$vars) {

$node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestion'] = 'node__solo';
  } else
  {
       $vars['theme_hook_suggestion'] = 'node__video';
  }
}

My field "field_solo" is correctly outputting a value of 0 or 1 also.

  • what is the template file name you used? and did you clear the cache? – Mohammed Shameem Feb 8 '13 at 16:38
  • Yes the cache is cleared. Template name: node--solo.tpl.php and node--video.tpl.php. – Dan Feb 8 '13 at 16:40
3

You can actually do that in the preprocess node function something like this:

function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestions'][] = 'node__theme1';
  } else
  {
       $vars['theme_hook_suggestions'][] = 'node__theme2';
  }

}

Here if the condition is true then the node template would be node--theme1.tpl.php

and if the condition is false then the tpl would be node--theme2.tpl.php.

  • Thanks Mohammed. Could you please add to your example above the condition of: if a field named 'field_solo' has a value of 1. – Dan Feb 8 '13 at 6:56
  • what is the type of the field is it just a check box? – Mohammed Shameem Feb 8 '13 at 7:03
  • any way I have updated the code do let me know if that works – Mohammed Shameem Feb 8 '13 at 7:07
  • I'm getting a server error with that Mohammed. I have a check box field of type Boolean (on or off). Any ideas? – Dan Feb 8 '13 at 15:39
  • could you post the error in the question. – Mohammed Shameem Feb 8 '13 at 15:40
2

Figured it out! I had to add "[und]" to the if statement:

$node = $vars['node'];
  if($node->field_solo['und'][0]['value'] == 1)
  {
       $vars['theme_hook_suggestion'] = 'node__solo';
  } else
  {
       $vars['theme_hook_suggestion'] = 'node__video';
  }


}
  • goo you got it :-) – Mohammed Shameem Feb 8 '13 at 17:31
  • 1
    @Dan I think there is a typo error. Its should be theme_hook_suggestions instead of theme_hook_suggestion – Md Eqbal Ahmad May 27 '16 at 6:54

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.