0

I have a custom theme template for my magento 1.9.1 and would like to add the "only X left" in my product list page. It is already in my product view page however I want it to show on every single product in the grid list page. How do I add to it?

3 Answers 3

2

Rather than instantiating the model for each product rather do this.

Create a magento module, and add these bits to it.

In the module config.xml

<frontend>
    <events>
        <catalog_product_collection_load_after>
            <class>your_module/observer</class>
            <method>addStockItemData</method>
        </catalog_product_collection_load_after>
    </events>
</frontend>

In the module observer

<?php 
// observer
public function addStockItemData($observer)
{
    $collection = $observer->getCollection();
    Mage::getSingleton('cataloginventory/stock')->addItemsToProducts($collection);
}

That will do the trick

1

You'd need to modify the theme's template/catalog/product/list.phtml file so that it included the required bits. That would be something like this under the grid mode and/or list mode depending on your site.

<?php $qty = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); ?>
<?php if ($qty): ?>
    Only <?php echo $qty; ?> left
<?php else: ?>
    Out of Stock
<?php endif; ?>

However that would only work for simple products and would probably say all configurable, grouped, or bundled ones are out of stock so you'd want to modify it a bit more to work with that if you use configurable, grouped, or bundled products.

3
  • Thank you. Do you know why I'm not getting the "out of stock" when my quantity is 0? It still says "Only 0.0000 left". Also I am getting a bunch of decimals. Do you know how can I get rid of the decimals?
    – James Tsai
    Commented Dec 29, 2014 at 18:47
  • Hi, I changed getQty to getStockQty and everything is good now. Thank you for your help! :)
    – James Tsai
    Commented Dec 29, 2014 at 19:11
  • For the 0.0000 you could force it to an integer by doing (int) before the Mage::getModel part. It should force it to 0 and then that would trigger as false in PHP for the if statement. Commented Dec 29, 2014 at 19:27
0

I've fixed the problem by editing /app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php file and added one line that seems to be missing in 1.9.1.0 (->addAttributeToSelect('*'))

$usedProducts = array();
$collection = $this->getUsedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions();

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.