add product to cart

piaoling  2011-08-01 11:08:27

    /**
     * Action list where need check enabled cookie
     *
     * @var array
     */
    protected $_cookieCheckActions = array('add');

    /**
     * Retrieve shopping cart model object
     *
     * @return Mage_Checkout_Model_Cart
     */
    protected function _getCart()
    {
        return Mage::getSingleton('checkout/cart');
    }

    /**
     * Get checkout session model instance
     *
     * @return Mage_Checkout_Model_Session
     */
    protected function _getSession()
    {
        return Mage::getSingleton('checkout/session');
    }

    /**
     * Get current active quote instance
     *
     * @return Mage_Sales_Model_Quote
     */
    protected function _getQuote()
    {
        return $this->_getCart()->getQuote();
    }

    /**
     * Set back redirect url to response
     *
     * @return Mage_Checkout_CartController
     */
    protected function _goBack()
    {
        $returnUrl = $this->getRequest()->getParam('return_url');
        if ($returnUrl) {
            // clear layout messages in case of external url redirect
            if ($this->_isUrlInternal($returnUrl)) {
                $this->_getSession()->getMessages(true);
            }
            $this->getResponse()->setRedirect($returnUrl);
        } elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
            && !$this->getRequest()->getParam('in_cart')
            && $backUrl = $this->_getRefererUrl()
        ) {
            $this->getResponse()->setRedirect($backUrl);
        } else {
            if (($this->getRequest()->getActionName() == 'add') && !$this->getRequest()->getParam('in_cart')) {
                $this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
            }
            $this->_redirect('checkout/cart');
        }
        return $this;
    }

    /**
     * Initialize product instance from request data
     *
     * @return Mage_Catalog_Model_Product || false
     */
    protected function _initProduct($ajax = null)
    {
        if($ajax == 'true')
            $productId = $this->getRequest()->getParam('product');
        else
        {
            $ref = $this->getRequest()->getParam('ref');
            $productId = (int) Mage::getModel('catalog/product')->getCollection()
                ->addAttributeToFilter('sku',$ref)
                ->getFirstItem()->getId();
        }

        if ($productId) {
            $product = Mage::getModel('catalog/product')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($productId);
            if ($product->getId()) {
                $status = $product->getStatus();
                if ($status==2){
                    $message = $this->__("product %s is disabled",$product->getName());
                    $this->_getSession()->addError($message);
                    return false;
                }
                return $product;
            }
        }
        else
            $this->_getSession()->addError($this->__('No product added.'));  
        return false;
    }

    protected function _getCartInfo()
    {
        $cartInfo = array();
        $cart = $this->_getCart();
        $cartInfo['qty'] = $cart->getSummaryQty().$this->__(' item(s)');
        $cartInfo['totals'] = Mage::helper('checkout')->formatPrice($cart->getQuote()->getGrandTotal());
        return $cartInfo;
    }

    /**
     * check the quote whether from quotation
     * @return bloor
     */
    protected function _checkQuotation()
    {
        $is_quotation = $this->_getCart()->getQuote()->getIsQuotation();
        $this->_getCart()->getQuote()->setIsQuotation(0)->save();
        if($is_quotation=='1')
            return true;
        return false;
    }

    /**
     * Add product to shopping cart action
     */
    public function addAction()
    {
        $cart   = $this->_getCart();

        //check quote whether from quotation
        if($this->_checkQuotation())
            $cart->truncate();

        $params = $this->getRequest()->getParams();
        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            //for ajax cart
            $ajax = $this->getRequest()->getParam('ajax');

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

            /**
             * Check product availability
             */
            if (!$product) {
                $this->_goBack();
                return;
            }

            $cart->addProduct($product, $params);
            if (!empty($related)) {
                $cart->addProductsByIds(explode(',', $related));
            }

            $cart->save();

            //when a grouped product is added to cart set each item is_from_group=1
            $tablePrefix = (string)Mage::getConfig()->getTablePrefix();
            $db = Mage::getSingleton('core/resource')->getConnection('core_write');
            if($product->getTypeId()=='grouped')
                foreach($cart->getQuote()->getItemsCollection() as $item)
                {
                    $sql = "update ".$tablePrefix."sales_flat_quote_item set is_from_group=1,group_id=".$product->getId()." where item_id=".$item->getItemId();
                    if($item->getItemId())
                        $db->query($sql);
                }

            $this->_getSession()->setCartWasUpdated(true);

            /**
             * @todo remove wishlist observer processAddToCart
             */
            Mage::dispatchEvent('checkout_cart_add_product_complete',
                array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
            );

            if (!$this->_getSession()->getNoCartRedirect(true)) {
                if (!$cart->getQuote()->getHasError()){
                    if($ajax=='true')
                    {
                        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($this->_getCartInfo()));
                        return;
                    }
                    else
                    {
                        $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
                        $this->_getSession()->addSuccess($message);
                    }
                }

                $this->_goBack();
            }
        } catch (Mage_Core_Exception $e) {
            if ($this->_getSession()->getUseNotice(true)) {
                $this->_getSession()->addNotice($e->getMessage());
            } else {
                $messages = array_unique(explode("n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->_getSession()->addError($message);
                }
            }

            $url = $this->_getSession()->getRedirectUrl(true);
            if ($url) {
                $this->getResponse()->setRedirect($url);
            } else {
                $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
            }
        } catch (Exception $e) {
            $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
            Mage::logException($e);
            $this->_goBack();
        }
    }

类别 :  magento(258)  |  浏览(4238)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: