Magento Attributes – Correct Syntax to Output Custom Attribute if Exists

attributes

This works perfectly, displaying a dropdown of products to offer as a free gift, the label for each option takes the name of the product.

<select id="select_28" class="product-custom-option" title="" name="freeGiftId">
    <option value=""><?php echo $this->__('-- Please Select --')?></option>
    <?php foreach($freeGifts as $giftId): ?>
    <?php $productGift = Mage::getModel('catalog/product')->load($giftId); ?>
    <option value="<?php echo $productGift->getId()?>">
        <?php echo $productGift->getName()?> /*THIS IS THE LINE IN QUESTION */
    </option>
    <?php endforeach; ?>
</select>

I've created a custom attribute however that will be outputted instead of the name but only if it exists.

I'll use <?php echo $productGift->getXyz(); ?> instead of <?php echo $productGift->getName()?>. But I need to add an if statement so that it is only shown if it exists.

I'm trying this and many other variations:-

<select id="select_28" class="product-custom-option" title="" name="freeGiftId">
    <option value=""><?php echo $this->__('-- Please Select --')?></option>
    <?php foreach($freeGifts as $giftId): ?>
    <?php $productGift = Mage::getModel('catalog/product')->load($giftId); ?>
    <option value="<?php echo $productGift->getId()?>">
        <?php if ($productGift->getXyz()): ?> /*THIS IS THE LINE IN QUESTION */
            <?php echo $productGift->getXyz(); ?>
        <?php else: ?>
            <?php echo $productGift->getName()?>
    </option>
    <?php endforeach; ?>
</select>

This isn't working though. Please could someone advise on the correct syntax to use in order to show custom attribute 'Xyz' if it exists, otherwise show the product 'name'?

Best Answer

You could use hasXyz to determine if the object has a value for that attribute, however assuming the value is truthy, what you have should work (it would fail if you expect it to be 0 or '').

EDIT: I can't remember for sure, but I think the closing endif is required in alternate syntax.

  <?php if ($productGift->getXyz()): ?> /*THIS IS THE LINE IN QUESTION */
      <?php echo $productGift->getXyz(); ?>
  <?php else: ?>
      <?php echo $productGift->getName()?>
  <?php endif; ?>