1

I need to print something conditionally in my node.tpl.php depending on the cck value of a field on my content type.

For example, if field_color has "red" or "blue", then print "It has color" and if it has other values print empty text.

1 Answer 1

2

The following should work:

if (isset($node->field_color[0]['value'])) {
  //If you want the field value to be displayed      
  print $node->field_color[0]['value'];
  //If you want some custom text to be displayed
  print 'It has colour';
} 
else {
  print 'Empty Text';
}

Or with ternary operators:

print (!empty($node->field_color[0]['value']) ? $node->field_color[0]['value'] : 'Empty text';

You'll probably either want to put in some logic to make sure the field exists though, or create a node-TYPE.tpl.php for your specific content type.

EDIT

This should sort out your red or blue issue:

if (isset($node->field_color[0]['value'])) {

  $colour_value = $node->field_color[0]['value'];

  if ($colour_value == 'red' || $colour_value == 'blue') {
    $colour = $colour_value;
  }
}

print (isset($colour)) ? $colour : t('Empty Text');

I've only put the field value into a variable to save space - you don't have to do this if you don't want to :-)

3
  • Go with the first one...the second one's over 80 characters :P
    – Clive
    Commented Jun 20, 2012 at 11:42
  • Thanks. But I would like to narrow down the condition of value to only "red" or "blue" and print "Empty Text" for the rest of the color (other than "red" or "blue").
    – chinita7
    Commented Jun 20, 2012 at 13:11
  • I've edited my answer. If the colour is user input, you might also want to run $colour through check_plain before outputting it!
    – Chapabu
    Commented Jun 20, 2012 at 13:48

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.