Search code examples
phpmagento

Magento: limit 3 products from category per order


I'm trying to set up a sample products category in Magento to allow people to select up to 3 free samples for every purchase, but how can I limit only 3 samples from that category per order?

[EDIT]

This is the current config.xml inside the dir app/code/local/MagePal/LimitCartProductByCategory/etc/config.xml:

<?xml version="1.0"?>
<config>
<modules>
    <MagePal_LimitCartProductByCategory>
        <version>1.0.1</version>
    </MagePal_LimitCartProductByCategory>
</modules>

<global>
    <models>
        <limitcartproductbycategory>
            <class>MagePal_LimitCartProductByCategory_Model_Observer</class>
        </limitcartproductbycategory>
    </models>
     <events>
        <checkout_cart_product_add_after>
            <observers>
                <limitcartproductbycategory>
                    <type>singleton</type>
                    <class>MagePal_LimitCartProductByCategory_Model_Observer</class>
                    <method>cartlimit</method>
                </limitcartproductbycategory>
            </observers>
        </checkout_cart_product_add_after>
    </events>
</global>
</config>

MagePal_EnableDuplicateProductStatus.xml in dir app/etc/modules/MagePal_LimitCartProductByCategory.xml:

<?xml version="1.0"?>
<config>
<modules>
    <MagePal_LimitCartProductByCategory>
        <active>true</active>
        <codePool>local</codePool>
    </MagePal_LimitCartProductByCategory>
</modules>
</config>

This is the current Observer.php inside the dir app/code/local/MagePal/LimitCartProductByCategory/Model/Observer.php:

class MagePal_LimitCartProductByCategory_Model_Observer 
{

public function cartlimit(Varien_Event_Observer  $observer)
{
    $category_ids = array();

    $quote = Mage::getSingleton('checkout/session')->getQuote();
    foreach($quote->getAllVisibleItems() as $item){
          $product = Mage::getModel('catalog/product')->load($item->getId());
          $product_category_ids = explode(",", $product->getCategoryIds());
          //$product_category_ids = $product->getCategoryIds();

          array_push($category_ids, $product_category_ids);
    }

    $justAdded = $observer->getQuoteItem();
    $justAddedCategoryIds = explode(",", $product->getCategoryIds());
    $justAddedId = in_array(58, $justAddedCategoryIds);


    $productJustAdded = Mage::getModel('catalog/product')->load($justAdded->getId());

    //total the catalogegory id in $category_ids
    //if $productJustAdded->getCategoryIds exist in $category_ids, 
    //then check to see if category id count greater than 3
    // if true then add error msg and try setting the qty to 0

    $freesample = 58;
    $tmp = array_count_values($category_ids);
    $cnt = $tmp[$freesample];

    echo $cnt;

    if ($justAddedId == true && $cnt > 3) {

        $quote->removeItem($justAdded->getId())->save();
        Mage::app()->getLayout()->getMessagesBlock()->setMessages('You can only have 3 free samples. Please remove a sample to add another.');
        Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml();
    }

    return $this;
}
}

Solution

  • Create an observer for event checkout_cart_product_add_after

    Take a look at my example @ Change Magento default status for duplicated products for help on how to create on observer

         <events>
            <checkout_cart_product_add_after>
                <observers>
                    <enableduplicateproductstatus>
                        <type>singleton</type>
                        <class>limitcartproductbycategory/observer</class>
                        <method>cartlimit</method>
                    </enableduplicateproductstatus>
                </observers>
            </checkout_cart_product_add_after>
        </events>
    

    Create: app/code/local/MagePal/LimitCartProductByCategory/Model/Observer.php

    class MagePal_LimitCartProductByCategory_Model_Observer 
    {
    
        public function cartlimit(Varien_Event_Observer  $observer)
        {
            $category_ids = array();
    
            $quote = Mage::getSingleton('checkout/session')->getQuote();
            foreach($quote->getAllVisibleItems() as $item){
                  $product = Mage::getModel('catalog/product')->load($item->getId());
                  $product_category_ids = explode(",", $product->getCategoryIds());
                  //$product_category_ids = $product->getCategoryIds();
    
                  array_push($category_ids, $product_category_ids);
            }
    
            $justAdded = $observer->getQuoteItem();
    
    
            $productJustAdded = Mage::getModel('catalog/product')->load($justAdded->getId());
    
            //total the category id in $category_ids
            //if $productJustAdded->getCategoryIds exist in $category_ids, 
            //then check to see if category id count greater than 3
            // if true then add error msg and try setting the qty to 0
    
            return $this;
        }
    }