0

Having trouble with a custom field. It's a plain text field, called special_note.

<?php $specnote = $_product->getResource()->getAttribute('special_note');
  if ($specnote) {
    echo "<div id='specialnote'>".$specnote->getFrontend()->getValue($_product)."</div>";
  }
?>  

The specialnote div is always showing up, even when there's data. I've tried variations like if (!empty($specnote)) and if (!isnull($specnote)) to no avail.

How do I make is so that the div only shows up when it's been populated?

Additional info: this is in the file /app/design/frontend/mytheme/theme/template/catalog/product/view.phtml

Field is set up in magento as a 'text field' - and the settings "Visible on Product View Page on Front-end" and "Used in Product Listing" are both set to yes.

3
  • 1
    Isn't this a liitle overhead? Why don't you use $_product->getSpecialNote()?
    – Thorsten
    May 23, 2014 at 6:59
  • It weirdly returns a blank space. like if I do <?php echo "<div>".$_product->getSpecialNote()."</div>" ?> - I get <div> </div> as a result.
    – SamC
    May 23, 2014 at 13:50
  • getSpecialNote was completely not returning anything for a while - reindex, then clear cache (the full cache storage), in that order.
    – SamC
    May 23, 2014 at 14:46

1 Answer 1

4
$specnote = $_product->getResource()->getAttribute('special_note');

Does not return the result you are expecting.
That code, returns an instance of the product attribute special_note If the attribute exists or an empty instance of a product attribute if the attribute does not exist. So if you use the result in an if statement it will always evaluate to true.
Try using this code:

<?php $specnote = trim($_product->getSpecialNote());?>
  if ($specnote) {
    echo "<div id='specialnote'>".$specnote."</div>";
  }
?> 
5
  • Ah. That info makes a lot of sense. However, your code returns a blank space, literally <div id='specialnote'> </div>. Some I'm wondering if I did something else incorrectly.
    – SamC
    May 23, 2014 at 14:00
  • As I noted above, if I do <?php echo "<div>".$_product->getSpecialNote()."</div>" ?> - I get <div> </div> - so getSpecialNote doesn't work at all, and I have no idea why that is.
    – SamC
    May 23, 2014 at 14:06
  • @SamC. I changed something. Try now. I added a trim
    – Marius
    May 23, 2014 at 14:07
  • Still nothing. I'm certain the field is set up right (added notes to my original Q about the config). Should I not have used the word 'special' or something?
    – SamC
    May 23, 2014 at 14:22
  • OH, scratch that. Must remember to dump caches between major edits. Also, minor typo - remove the ?> at the end of the the first line.
    – SamC
    May 23, 2014 at 14:45

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.