Jump to content

Magento Own Custom Module for add-to-cart Not Working


aveeva

Recommended Posts

Created module like No other products add to cart if restricted product available in cart and vice versa.

My Module :

  • app/etc/modules/Brst_Test.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Brst_Test>
            <active>true</active>
            <codePool>community</codePool>
        </Brst_Test>
    </modules>
</config>

This is my observer file

  • app/code/community/Brst/Test/Model/Observer.php
<?php
ini_set('display_errors', '1');

// Mage::log('Hy observer called', null, 'logfile.log');
class Brst_Test_Model_Observer
{
    //Put any event as per your requirement
    public function logCartAdd() {
        $product = Mage::getModel('catalog/product')
                        ->load(Mage::app()->getRequest()->getParam('product', 0));
        $cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

        if ($product->getId()==31588 && cart_qty > 0) {
            Mage::throwException("You can not add This special Product, empty cart before add it");
        }

        // $quote = Mage::getSingleton('checkout/session')->getQuote();
        // if ($quote->hasProductId(2)) 
        //{
        //  Mage::getSingleton("core/session")->addError("Cart has Special Product you can not add another");
        //  return;
        // }
        $quote = Mage::getModel('checkout/cart')->getQuote();
        foreach ($quote->getAllItems() as $item) {
            $productId = $item->getProductId();
            if($productId==31588){
                Mage::throwException("Cart has Special Product you can not add another");
            }
        }

    }
}
?>

 

  • app/code/community/Brst/Test/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Brst_Test>
           <version>0.1.0</version>
        </Brst_Test>
    </modules>
    <global>
        <models>
            <brst_test>
                <class>Brst_Test_Model</class>
            </brst_test>
        </models>
    </global>
    <frontend>
        <events>
            <controller_action_predispatch_checkout_cart_add>
                <observers>
                    <brst_test_log_cart_add>
                        <class>brst_test/observer</class>
                        <method>logCartAdd</method>
                    </brst_test_log_cart_add>
                </observers>
            </controller_action_predispatch_checkout_cart_add>
        </events>
    </frontend>
</config>

 

Not working, how to solve the error?

 
Link to comment
Share on other sites

@NotionCommotion If i try with try and cache debug, no error, 

 

 

<?php
ini_set('display_errors', '1');

 Mage::log('Hy observer called', null, 'add_to_cart_logfile.log');
class Brst_Test_Model_Observer
{
    //Put any event as per your requirement
    public function logCartAdd() {
        try{
        Mage::log('test', null, 'add_to_cart_logfile.log');
        $product = Mage::getModel('catalog/product')
                        ->load(Mage::app()->getRequest()->getParam('product', 0));
        $cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

        if ($product->getId()==31588 && cart_qty > 0) {
            Mage::throwException("You can not add This special Product, empty cart before add it");
        }

        // $quote = Mage::getSingleton('checkout/session')->getQuote();
        // if ($quote->hasProductId(2)) 
        //{
        //  Mage::getSingleton("core/session")->addError("Cart has Special Product you can not add another");
        //  return;
        // }
        $quote = Mage::getModel('checkout/cart')->getQuote();
        foreach ($quote->getAllItems() as $item) {
            $productId = $item->getProductId();
            if($productId==31588){
                Mage::throwException("Cart has Special Product you can not add another");
            }
        }
        }catch(Exception $e)
        {
            Mage::log($e, null, 'add_to_cart_logfile.log');
        }

    }
}
?>

 

Link to comment
Share on other sites

aveeva,  cart_qty should be $cart_qty.  More importantly, you should have received an undeclared constant warning.  First execute the below script.

<?php
ini_set('display_errors', '1');
$cart_qty = 123;

if (cart_qty > 0) {
   exit("You can not add This special Product, empty cart before add it");
}
exit('done');

Did you receive a warning?  If not, your error logging is not set up write, and figure this out before doing any more work or you will definitely have a horrible experience.

If you did receive a warning, then this erroneous line of code is not being executed.  Add some flags to your script (i.e. echo('got here!'); ) to figure out where you are going wrong.

Link to comment
Share on other sites

If i run below code in observer.php there is no warning:

<?php
ini_set('display_errors', '1');
$cart_qty = 123;

if (cart_qty > 0) {
   exit("You can not add This special Product, empty cart before add it");
}
exit('done');

 

Link to comment
Share on other sites

I just try with try cache error handling :

 

<?php
ini_set('display_errors', '1');

Mage::log('fine dude', null, 'logfile.log');
class Brst_Test_Model_Observer
{
    //Put any event as per your requirement
    public function logCartAdd() {
        Mage::log('good dude', null, 'logfile.log');
        try{
        $product = Mage::getModel('catalog/product')
                        ->load(Mage::app()->getRequest()->getParam('product', 0));
        $cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

        if ($product->getId()==31588 && $cart_qty > 0) {
            Mage::throwException("You can not add This special Product, empty cart before add it");
        }

        // $quote = Mage::getSingleton('checkout/session')->getQuote();
        // if ($quote->hasProductId(2)) 
        //{
        //  Mage::getSingleton("core/session")->addError("Cart has Special Product you can not add another");
        //  return;
        // }
        $quote = Mage::getModel('checkout/cart')->getQuote();
        foreach ($quote->getAllItems() as $item) {
            $productId = $item->getProductId();
            if($productId==31588){
                Mage::throwException("Cart has Special Product you can not add another");
            }
        }
    }catch(Exception $e)
    {
        // Mage::log($e, null, 'logfile.log');
        echo $e->getMessage();
    }

    }
}
?>

and my logfile.log file

 

2019-06-28T05:50:11+00:00 DEBUG (7) : fine dude
2019-06-28T05:50:11+00:00 DEBUG (7) : good dude

If i am right?

Edited by aveeva
Link to comment
Share on other sites

17 hours ago, NotionCommotion said:

Are you getting any errors?  Maybe on this line?


if ($product->getId()==31588 && cart_qty > 0) {

 

It won't throw an error, just a notice, so it will depend on the error reporting level.

Notice: Use of undefined constant cart_qty 

It will assume it is the string value 'cart_qty'.

Link to comment
Share on other sites

After correcting the syntax error, my logic not working but observer triggered.

 

<?php
ini_set('display_errors', '1');

Mage::log('fine dude', null, 'logfile.log');
class Brst_Test_Model_Observer
{
    //Put any event as per your requirement
    public function logCartAdd() {
        Mage::log('good dude', null, 'logfile.log');

        // try{

        $product = Mage::getModel('catalog/product')
                        ->load(Mage::app()->getRequest()->getParam('product', 0));
        $cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

        if ($product->getId()==31588 && $cart_qty > 0) {
            Mage::throwException("You can not add This special Product, empty cart before add it");
        }

        // $quote = Mage::getSingleton('checkout/session')->getQuote();
        // if ($quote->hasProductId(2)) 
        //{
        //  Mage::getSingleton("core/session")->addError("Cart has Special Product you can not add another");
        //  return;
        // }
        $quote = Mage::getModel('checkout/cart')->getQuote();
        foreach ($quote->getAllItems() as $item) {
            $productId = $item->getProductId();
            if($productId==31588){
                Mage::throwException("Cart has Special Product you can not add another");
            }
        }

    // }catch(Exception $e)
    // {
    //     // Mage::log($e, null, 'logfile.log');
    //     echo $e->getMessage();
    // }

    }
}
?>

finally not working but observer triggered,  still other products added to cart if restricted products available in cart. How to do my module a better way?

FYI: logfile.log

 

2019-06-28T06:05:00+00:00 DEBUG (7): fine dude
2019-06-28T06:05:00+00:00 DEBUG (7): good dude

 

Edited by aveeva
Link to comment
Share on other sites

  • 1 month later...

@Barand  I just try with category instead of products, here i am facing some issue, could you pls help me, 

public function cartevent(Varien_Event_Observer $observer)
		{
			// $category_id = array(680, 894, 895) ; //category ids
			
			$category_products  = Mage::getModel('catalog/category')
								->addAttributeToFilter('category_id', array('in' => array('680','894','895')))
								->setWebsiteId(2);			    // load website id		

			// check cart qty status							
			$cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemQty();  
			
			//logic
			if($category_products && $cart_qty > 0  )
			{
				Mage::throwException("If you want Kolu Padi, Purchase alone not mixed with other Products");	
			}
			
			 //check if cart have products 
			 $quote = Mage::getModel('checkout/cart')->getQuote();

			foreach($quote->getAllItems() as $item)
			{
				$productId	= $item->getCategoryId();
				
				if($productId == $category_products)
				{
					Mage::throwException("Cart has Special Product you can not add another");
				}
			}	 
		}

Observer not trigger. could you pls help me

Link to comment
Share on other sites

@Barand

@NotionCommotion

 

On 6/27/2019 at 5:47 PM, NotionCommotion said:

Are you getting any errors?  Maybe on this line?


if ($product->getId()==31588 && cart_qty > 0) {

 

Like same how can i get category_id,  my observer :

 

<?php
class Gta_KolupadiRestrict_Model_Observer {

	public function cartevent(Varien_Event_Observer $observer) {

		// Load product
		$product = $observer->getProduct();
		$prodID = $product->getId();
		$_product = Mage::getModel('catalog/product')->load($prodID);

		// get category id
		$categoryIds = $_product->getCategoryIds();

		// check cart
		$cart_qty = (int)Mage::getModel('checkout/cart')->getQuote()->getItemQty();

		// check conditiion cart has other products 
		if(in_array(681, $categoryIds) && $cart_qty > 0) {
			Mage::throwException("You can not add This special Product, empty cart before add it");
		}
	
		// check if other products add to cart
		$quote = Mage::getModel('checkout/cart')->getQuote();
		foreach ($quote->getAllItems() as $item) {
			$_product1 = $item->getProduct();
	
			$categoryIds1 = $_product1->getCategoryIds();
			if(in_array(681, $categoryIds1)) {
				Mage::throwException("If you want Kolu Padi, Purchase alone not mixed with other Products");
				break;
			}
		}
	}   
}
?>

 

condition :

I just want to restrict some of the category of products to purchase with other category products,

Workout :

If customer click add to cart, using observer compare current add-to-cart product category id & already cart products category id, if the current product category id and cart products category id different display message like, You can not add This special Product, empty cart before add it

and also vice versa if cart has restricted category of products, if customer try to add other products throw exception like If you want Kolu Padi, Purchase alone not mixed with other Products

 

My error :

 

a:5:{i:0;s:67:"If you want Kolu Padi, Purchase alone not mixed with other Products";i:1;s:1835:"#0 /home/abc/public_html/app/code/local/Gta/KolupadiRestrict/Model/Observer.php(21): Mage::throwException('If you want Kol...')
#1 /home/abc/public_html/app/code/core/Mage/Core/Model/App.php(1358): Gta_KolupadiRestrict_Model_Observer->cartevent(Object(Varien_Event_Observer))
#2 /home/abc/public_html/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Gta_KolupadiRestrict_Model_Observer), 'cartevent', Object(Varien_Event_Observer))
#3 /home/abc/public_html/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('checkout_cart_p...', Array)
#4 /home/abc/public_html/app/code/core/Mage/Checkout/Model/Cart.php(290): Mage::dispatchEvent('checkout_cart_p...', Array)
#5 /home/abc/public_html/app/code/local/Cmsmart/AjaxCart/controllers/IndexController.php(315): Mage_Checkout_Model_Cart->addProduct('5071', Array)
#6 /home/abc/public_html/app/code/local/Cmsmart/AjaxCart/controllers/IndexController.php(133): Cmsmart_AjaxCart_IndexController->tryaddAction(Object(Mage_Catalog_Model_Product), Array)
#7 /home/abc/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Cmsmart_AjaxCart_IndexController->indexAction()
#8 /home/abc/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('index')
#9 /home/abc/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#10 /home/abc/public_html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#11 /home/abc/public_html/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#12 /home/abc/public_html/australia/index.php(93): Mage::run('australia', 'website')
#13 {main}";s:3:"url";s:100:"/ajaxcart/index/index/?form_key=MtlJbvKkqPQKCLJR&product=5071&related_product=&qty=1&_=1565155804563";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:9:"australia";}

 

Edited by aveeva
Link to comment
Share on other sites

config.xml

 

<?xml version="1.0"?>
<config>
    <modules>
        <Gta_KolupadiRestrict>
            <version>1.0.0</version>
        </Gta_KolupadiRestrict>
    </modules>
    <global> 
        <models>
            <gta_kolupadirestrict>
                <class>Gta_KolupadiRestrict_Model</class>
            </gta_kolupadirestrict>
        </models>
        <events>
            <checkout_cart_product_add_after>
                <observers>
                    <Gta_KolupadiRestrict_Model_Observer>   
                        <type>singleton</type>
                        <class>Gta_KolupadiRestrict_Model_Observer</class>
                        <method>cartevent</method>
                    </Gta_KolupadiRestrict_Model_Observer>
                </observers>
            </checkout_cart_product_add_after>      
        </events>
    </global>  
</config>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.