'How to disallow mix and match of products in my Magento cart for preorders

I am selling pre-orders in my store. And for bookkeeping reasons, I cannot let customers buy both regular and pre-order products in the same order. All pre-orders have the attribute "preorder" set to Yes.

Now I need to disallow my customers to place regular products along with pre-order products in the same shopping cart. Preferably by generating a "You cannot mix regular products with pre-order products" message when customers are trying to do exactly this.

Any idea of how to achieve this?



Solution 1:[1]

You can use an observer to do your job. Unfortunately Magento doesn't have an event to be fired before the user adds something to cart. So Magento itself actually uses the checkout_cart_product_add_afterevent. So create the following module:

app/code/local/My/Eventlistener/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <My_Eventlistener>
            <version>1.0.0</version>
        </My_Eventlistener>
    </modules>
    <global>
        <models>
            <my_eventlistener>
                <class>My_Eventlistener_Model</class>
            </my_eventlistener>
        </models>
    </global>
    <frontend>
        <events>
            <checkout_cart_product_add_after>
                <observers>
                    <my_checkout_cart_product_add_afte>
                        <class>my_eventlistener/observer</class>
                        <method>checkoutCartProductAddAfter</method>
                    </my_checkout_cart_product_add_after>
                </observers>
            </checkout_cart_product_add_after>
        </events>
    </frontend>
</config>

app/etc/modules/My_Eventlistener.xml

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

app/code/local/My/Eventlistener/Model/Observer.php

<?php
 
class My_Eventlistener_Model_Observer
{
    public function checkoutCartProductAddAfter() {
        $quoteItem = $observer->getEvent()->getQuoteItem();
        $product = $observer->getEvent()->getProduct();
        $quote = $quoteItem->getQuote();

        //Flag that becomes true if he has mixed products.
        $he_has_mixed_products = false;

        /*
         *    Check here if he has mixed products in his cart
         */

        if( $he_has_mixed_products )
            $quote->removeItem($quoteItem->getId());
            Mage::throwException('You cannot mix regular products with pre order products!');
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TylerH