Merchant Stories

Magento Modules: Limiting Number of Shopping Cart Products

Jan 14, 2015 5 min read 346 views
Listen audio
Magento Modules: Limiting Number of Shopping Cart Products

In the 21st century, eCommerce has grown extremely popular and it does not look like it is losing its popularity. Small entrepreneurs and businesses of the marketing sphere rarely encounter any problems with the site operation directly in the process of selling products through an online store.

However, the sites of large suppliers and retailers whose orders’ count reaches several thousand a day often stop reacting to any manipulations or commands.

In this article, we will discuss how to create Magento modules that will limit the number of products allowed in storefront shopping carts to be limited on a per customer basis. This extension will only affect products with different SKUs while multiple items of the same products can be added without any limitations.

Working With Magento Modules

So, the first step will be the creation of a quote (limit) file, it will be at app/etc/modules/Obiwan_QuoteLimit.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Obiwan_QuoteLimit>
            <active>true</active>
            <codePool>community</codePool>
        </Obiwan_QuoteLimit>
    </modules>
</config>

 

 

Then, we use the event/observer mechanism with the help of which we can inform users that their product limits have been reached. But first, we need to identify that limit. You can set any number in your admin panel, and set a default value, e.g. 100. Then you need to create a configuration file for your module: app/code/community/Obiwan/QuoteLimit/etc/config.xml.

<?xml version="1.0"?>
<config>
    <modules>
        <Obiwan_QuoteLimit>
            <version>0.1.0</version>
        </Obiwan_QuoteLimit>
    </modules>
    <global>
        <models>
            <obiwan_quotelimit>
                <class>Obiwan_QuoteLimit_Model</class>
            </obiwan_quotelimit>
        </models>
        <helpers>
            <obiwan_quotelimit>
                <class>Obiwan_QuoteLimit_Helper</class>
            </obiwan_quotelimit>
        </helpers>
    </global>
    <frontend>
        <events>
            <sales_quote_save_before>
                <observers>
                    <obiwan_quotelimit_singleOrderLimit>
                        <class>obiwan_quotelimit/observer</class>
                        <method>singleOrderLimit</method>
                    </obiwan_quotelimit_singleOrderLimit>
                </observers>
            </sales_quote_save_before>
        </events>
    </frontend>
    <default>
        <obiwan_quotelimit>
            <general>
                <active>1</active>
                <single_order_top_items>100</single_order_top_items>
                <single_order_top_items_msg><![CDATA[No single order allowed with items 
                over %s.]]></single_order_top_items_msg>
            </general>
        </obiwan_quotelimit>
    </default>
    <adminhtml>
        <acl>
            <resources>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <obiwan_quotelimit translate="title" 
                                        module="obiwan_quotelimit">
                                            <title>Maximum Quote Items</title>
                                        </obiwan_quotelimit>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
    </adminhtml>
</config>

 

 

Using the above code we have identified the event sales_quote_save_before which was created to preserve the ‘quote’ during the process of filling the shopping cart. Also, you can set a maximum default number in this file.  You can create a message indicating that the limit is reached.

The next step would be the creation of a file for configuration of a maximum number of products by the store administrator in the admin panel: System->Configuration->Obi-Wan->General->Maximum Quote Items. We should create a file app/code/community/Obiwan/QuoteLimit/etc/system.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <tabs>
        <obiwan translate="label" module="obiwan_quotelimit">
            <label>Obi-Wan</label>
            <sort_order>150</sort_order>
        </obiwan>
    </tabs>
    <sections>
        <obiwan_quotelimit translate="label comment" module="obiwan_quotelimit">
            <class>separator-top</class>
            <label>Maximum Quote Items</label>
            <tab>obiwan</tab>
            <frontend_type>text</frontend_type>
            <sort_order>100</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <general translate="label">
                    <label>Maximum Quote Items</label>
                    <sort_order>51</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <active translate="label">
                            <label>Enable</label>
                            <sort_order>10</sort_order>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno
                            </source_model>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </active>
                        <single_order_top_items>
                            <label>Single Order Maximum Items</label>
                            <comment><![CDATA[No single order can be placed over X items, 
                            where X is an integer value which defaults to 100.]]></comment>
                            <frontend_type>text</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </single_order_top_items>
                        <single_order_top_items_msg>
                            <label>Single Order Maximum Items Message</label>
                            <comment><![CDATA[Message to be displayed to customer when 
                            "Single Order Maximum Items" condition limit is triggered. 
                            Defaults to "No single order allowed with items over %s.". 
                            Please use "%s" to position the amount items within the 
                            message string.]]></comment>
                            <frontend_type>text</frontend_type>
                            <sort_order>30</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </single_order_top_items_msg>
                    </fields>
                </general>
            </groups>
        </obiwan_quotelimit>
    </sections>
</config>

 

 

The next step is the creation of an auxiliary file ‘helper’. It will help to get the data for various configurations. Create the file app/code/community/Obiwan/QuoteLimit/Helper/Data.php:

<?php
class Obiwan_QuoteLimit_Helper_Data extends Mage_Core_Helper_Abstract
{
    const XML_PATH_ACTIVE                     = 'obiwan_quotelimit/general/active';
    const XML_PATH_SINGLE_ORDER_TOP_ITEMS     = 'obiwan_quotelimit/general/single_order_
    top_items';
    const XML_PATH_SINGLE_ORDER_TOP_ITEMS_MSG = 'obiwan_quotelimit/general/single_order_
    top_items_msg';

    public function isModuleEnabled($moduleName = null)
    {
        if ((int)Mage::getStoreConfig(self::XML_PATH_ACTIVE, Mage::app()->getStore()) != 1) 
        {
            return false;
        }

        return parent::isModuleEnabled($moduleName);
    }

    public function getSingleOrderTopItems($store = null)
    {
        return (int)Mage::getStoreConfig(self::XML_PATH_SINGLE_ORDER_TOP_ITEMS, $store);
    }

    public function getSingleOrderTopItemsMsg($store = null)
    {
        return Mage::getStoreConfig(self::XML_PATH_SINGLE_ORDER_TOP_ITEMS_MSG, $store);
    }
}

 

The last step is the creation of a file which performs all the main work to limit the number of products in the shopping cart – app/code/community/Obiwan/QuoteLimit/Model/Observer.php:

<?php
class Obiwan_QuoteLimit_Model_Observer
{
    protected $_helper;

    public function __construct()
    {
        $this->_helper = Mage::helper('obiwan_quotelimit');
    }

    /**
     * No single order can be placed over are items of X
     * @param   Varien_Event_Observer $observer
     */
    public function singleOrderLimit($observer)
    {
        if (!$this->_helper->isModuleEnabled()) {
            return;
        }

        /* @var Mage_Sales_Model_Quote $quote */
        $quote = $observer->getEvent()->getQuote();
        $store = $quote->getStore();

        if ($quote->getItemsCount() > $this->_helper->getSingleOrderTopItems($store)) {

            $topItems = $this->_helper->getSingleOrderTopItems($store);

            Mage::getSingleton('checkout/session')->addError(
                $this->_helper->__($this->_helper->getSingleOrderTopItemsMsg($store), 
                $topItems));

            Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::
            getUrl('checkout/cart'));
            Mage::app()->getResponse()->sendResponse();
            exit;
        }
    }
}

 

 

How does it work?

First, the system determines the value of the ‘quote’, then checks the number of products in the cart and compares the numbers. If the product number limit is not reached the purchase is made properly, but if the number has exceeded the quota set by the administrator, a customer will see a message that the limit has been exceeded and then the system will return them to the cart without saving the order, i.e. the cart will be cleaned.

You can find more information about the most interesting and sometimes irreplaceable Magento modules on the GoMage site and in our blog.

That's where you contact us!

    By submitting this form you agree to GoMage's Terms of Use and Privacy Policy
    woo-hoo! Now its time to keep checking your inbox, as we will be getting in touch soon. Promise :)
    oops! Thanks. But it seems like some kind of technical issues stop you from meeting GOMAGE. Could you try again?