Displaying Magento Custom Attributes in list.phtml

In a recent Magento project, I had to display a date when a product would be back in stock. This is fairly straight forward. Create a custom attribute of a date type (stock_due_date) and assign the attribute to the attribute set.

In the my code on product/view.phtml if could easily output the formatted date like so:

<?php else: ?>
 <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
<?php
 $stock_date = $_helper->productAttribute($_product, $_product->getStockDueDate(), 'stock_due_date');
 $format = 'long';
 ?>
 <p class="availability out-of-stock"><?php echo $this->__('Due in Stock:') ?><span><?php echo Mage::helper('core')->formatDate($stock_date, $format, $showTime = false); ?></span></p>
 <?php endif; ?>

This worked like a charm but then the client asked for it to also show on the product list.phtml page. So I copied the code into list.phtml and voila – it kept¬†showing today’s date! This is because of two related issues:

  1. $_product->getStockDueDate() was returning null
  2. formateDate() will use today’s date if fed a null date.

The reason¬†getStockDueDate() returned null was that the attribute, stock_due_date, was not included in the list collection. So, I set “Used in Product Listing” to Yes for the attribute and reindexed. Unfortunately this didn’t work as expected and I had to turn off “Use Flat Catalog Product”, reindex and then re-enable “Use Flat Catalog Product” and reindex again.

Now the stock due date was displaying as expected. However, further testing threw up another issue. If I deleted the stock due date on a product and saved, today’s date would show up on that product but not on products that had never had a stock_due_date set.

So, I had to check that stock_due_date existed before outputting it like so:

<?php if ($stock_date): ?>
 <p class="availability out-of-stock"><?php echo $this->__('Due in Stock:') ?><span><?php echo Mage::helper('core')->formatDate($stock_date, $format, $showTime = false); ?></span></p>
 <?php endif; ?>

It seems that once an attribute (at least of date type) has been populated, Magento never truly returns it as a null attribute.

The following two tabs change content below.
Web developer and Magento SEO & Sales Optimisation specialist.

Latest posts by Eddie May (see all)