Add to Cart – How to Add a Product to the Cart via Querystring Using SKU

addtocartquerysku

I know that we can adding a product to cart via querystring.
but how do we add sku to cart via querystring in url without including product id
like this :

domain/checkout/cart/add?sku=ABC
or
domain/checkout/cart/add/sku=BC

Best Answer

Andhi Irawan,you can not do this type of work at checkout Cart controllers. If want this type of work then you need to rewrite Checkout CartController.php and on this class magento is load the product object by id before going to cart,So you need load product by sku on this place .

Step 1: rewrite cartController.php and code is for xml rewrite

   <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <customcart before="Mage_Checkout">YourNameSpace_YourMOdule</customcart>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>  

Step2: and on your extended Cartcontorller _initProduct function you need product load product by sku

     protected function _initProduct()
  {
    $sku=$this->getRequest()->setParam('sku');
    $_catalog = Mage::getModel('catalog/product');
    $idBySku = $_catalog->getIdBySku($sku);

    if ($idBySku) { 
        $productId = $idBySku;
    $this->getRequest()->setParam('product', $productId );
    }else{
    $productId = (int) $this->getRequest()->getParam('product');
    }
    if ($productId) {
        $product = Mage::getModel('catalog/product')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->load($productId);
        if ($product->getId()) {
        return $product;
        }
    }

        return false;
    }

How to rewrite controller see more at : http://www.amitbera.com/how-to-override-a-controller-in-magento/

Related Topic