0

Could it be possible to throw an exception flag if a user tried to add products that are not in the same category as the items already in their cart? Much the same way that Magento throws a flag if a user tries to add both a Nominal and Regular product to the same cart.

1 Answer 1

1

I have written the sample code, this link is the actual answer that will work for you:

Create an observer for event checkout_cart_product_add_after

<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;
    }
}
1
  • Is this complete code? I tried and its not working
    – Indian
    Commented Oct 12, 2017 at 11:31

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.