简体   繁体   中英

Magento allow product add to cart if another category product added

I have a store with few categories which are shirt, trousers, accessories,....etc. If user click add to cart button of the trouser then check if already added the shirt before add this trouser to the cart. The purpose is allow users to add a shirt before they add a trouser.

Can I do using ajax ?

If anyone have solutions appreciate that. Thank you

You can create your own extension for this but the simple way for this is.

First you can create product attribute let's say "related_category"

and use below extension for Ajax add to cart.

https://www.magentocommerce.com/magento-connect/ajaxcart-3-15606.html

In this extension open this file

[app\\code\\local\\Hardik\\Ajaxcart\\controllers\\Checkout\\CartController.php]

and find below code.

$related = $this->getRequest()->getParam('related_product');

add this code after this line [here i have fetch category ids from new created attribute called "related_category"].

    $related_category = Mage::getModel('catalog/product')->load($product->getId())->getRelatedCategory();
    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $cartItems = $quote->getAllVisibleItems(); $available = 'false';
    foreach ($cartItems as $item) {
        $productId = $item->getProductId();
        $_product = Mage::getModel('catalog/product')->load($productId);
        $productCats = $_product->getCategoryIds();
        if (count(array_intersect($related_category,$productCats))) {
            $available = 'true'; break;
        }
    }

    if($available == 'false'){
        $_response = Mage::getModel('ajaxcart/response');
        $_response->setError(true);

        $messages = array_unique(explode("\n", "Please add related product first!"));
        $json_messages = array();
        foreach ($messages as $message) {
            $json_messages[] = Mage::helper('core')->escapeHtml($message);
        }
        $_response->setMessages($json_messages);
        $url = $this->_getSession()->getRedirectUrl(true);
        $_response->send();
    }

In Above code i have fetch related category and check in cart whether there products are available or not if it's available [$available = 'true'] add to cart will work normally otherwise [$available = 'false'] it will give error like "Please add related product first!"

So, whenever customer purchase "trouser" and in related_category attribute of this product you have set "shirts" category id it will ask to add shirts product first.

So, i hope this solution work for you. please check this and let me know in case of any query.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM