Discussions

Print out a Drupal Commerce field only if it has a value

In Drupal Commerce, you can use the following to print out a field in your node.tpl.php file:

<?php
 
print render($content['product:field_NAME']);
?>

But how do you print a field only if it has content?

For a normal Drupal field you would use the following:

<?php
if (isset ($node->field_NAME)):
  print
$node->field_NAME['und'][0]['safe_value'];
endif;
?>

But that doesn't work with a Drupal commerce field. I would appreciate if someone could offer any pointers!

Posted: Apr 5, 2012

Comments

Joel Wallis Jucá on February 10, 2013

There's no Drupal Commerce field, only entity fields, which can be a node (a product display) or a commerce_product (the product itself). If you need to check a field from the node, check it from the node. If you need to check from the commerce_product, check from it.

<?php
// let's assume we are in the /node/123 path, where we see a product display node
$commerce_product = commerce_product_load($node->field_your_productreference_field[$node->language][0]['product_id']);

if(isset(
$commerce_product->field_some_useful_field[LANGUAGE_NONE][0]['value'])) {
 
// use the render() here
}
?>

harry_nc on October 24, 2013

Sorry but thanks for a fabulously unhelpful comment, that does not explain nor help with the solution to the problem.