Monday, November 23, 2009

Link to first product in category, dynamically (for marcfalk)

This is a response for http://www.magentocommerce.com/boards/viewthread/67625/
Problem: Create a link to the first(smallest id) in stock product in a category.
This is the code to retrieve the first product in stock with the smallest id:
(Let's assume the category id you want to do it for is $categoryId)
$_category = Mage::getModel('catalog/category')->load($categoryId);
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addCategoryFilter($_category);
$collection->getSelect()->joinLeft(
array('_inventory_table'=>$collection->getResource()->getTable('cataloginventory/stock_item')),
"_inventory_table.product_id = e.entity_id",
array('is_in_stock', 'manage_stock')
);
$collection->addExpressionAttributeToSelect('on_top',
'(CASE WHEN (((_inventory_table.use_config_manage_stock = 1) AND (_inventory_table.is_in_stock = 1)) OR  ((_inventory_table.use_config_manage_stock = 0) AND (1 - _inventory_table.manage_stock + _inventory_table.is_in_stock >= 1))) THEN 1 ELSE 0 END)',
array());
$collection->getSelect()->order('on_top DESC');
$collection->getSelect()->order('entity_id ASC');
$collection->getSelect()->limit('1');
if ($collection->count() > 0){
$_product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($collection->getFirstItem()->getId());
}
else{
$_product = Mage::getModel('catalog/product');
}

After that in order to print the product url do this:
<?php if ($_product->getId()) : ?>
<a href="<?php echo $_product->getUrl()?>"> First in stock product in category A  (or <?php echo $_product->getName(); ?>)</a>
<?php endif;?>

In case the category has no products at all the link above will not be displayed.
In case all the products in the category are out of stock the link will point to the product with the smallest id.
if you want in this case not to display the link change the if above into:
<?php if ($_product->getId() && $_product->isSalable()) : ?>

2 comments:

  1. Hello,

    Where do i need to put this code?

    Greetz Peter

    ReplyDelete
  2. Good question Peter.
    I wrote this a long time ago.
    Check this: http://www.magentocommerce.com/boards/viewthread/67625/#t194715
    with one minor change. Do not put the code directly in the core file. Properly override the Category model. Here is how: http://magedev.com/2009/06/03/magento-overriding-model-block-or-helper/

    ReplyDelete