Magento 2以编程方式将产品添加到购物车时,迷你购物车产品价格变为零($ 0.00)

时间:2018-05-01 05:22:17

标签: php magento2

我创建了一个模块,用于以编程方式在循环中将产品添加到购物车中。当我们运行这个控制器代码时,它将在购物车页面显示价格的产品,但在迷你购物车显示产品价格为0.00美元。 我的控制器代码如下所示。

<?php

namespace Mageniks\Customaddtocart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;

class Addtocart extends Action
{
    protected $_resultPageFactory;
    protected $_storeManager;
    protected $productRepository;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;
    protected $_productloader;
    protected $cartRepository;
    protected $quoteManagement;
    protected $_customerSession;
    protected $quoteFactory;
    public function __construct(Context $context,
                                \Magento\Store\Model\StoreManagerInterface $storeManager,
                                \Magento\Catalog\Model\ProductRepository $productRepository,
                                \Magento\Checkout\Model\Session $checkoutSession,
                                \Magento\Checkout\Model\Cart $cart,
                                PageFactory $resultPageFactory,
                                \Magento\Catalog\Model\ProductFactory $_productloader,
                                \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
                                \Magento\Quote\Api\CartManagementInterface $quoteManagement,
                                \Magento\Customer\Model\Session $customerSession,
                                \Magento\Customer\Model\CustomerFactory $customerFactory,
                                \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
                                \Magento\Quote\Model\QuoteFactory $quoteFactory)
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;
        $this->productRepository = $productRepository;
        $this->_storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->cart = $cart;
        $this->cartRepository = $cartRepository;
        $this->_productloader = $_productloader;
        $this->quoteManagement = $quoteManagement;
        $this->_customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->quoteFactory = $quoteFactory;
    }

    protected function addProduct($products)
    {
         // Note : $products peramater contain all product information.
        $quote = $this->_checkoutSession->getQuote();
        foreach($products as $params)
        {
            $cartparams = array();          
           $productId = $this->_objectManager->create('Magento\Catalog\Model\Product')->getIdBySku($params['sku']);     
           $product = $this->_productloader->create()->load($productId);
            if (!$product) {
                return false;
            }
            $cartparams['product'] = $product->getId();            
            $customOptions = $this->_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);

                foreach ($customOptions as $option) 
                {
                    if($option['title'] == "option1")
                    {                       
                            $cartparams['options'][$option['option_id']] = "Color : black";
                    }
                    else if($option['title'] == "option2")
                    {


                            $cartparams['options'][$option['option_id']] = "Color : white";


                    }else
                    {
                        $cartparams['options'][$option['option_id']] = "";
                    }
                }



            if (isset($params['qty'])) {
                $cartparams['qty'] = $params['qty'];
            } else {
                $cartparams['qty'] = 1;
            }
            try {


                 $this->cart->addProduct($product, $cartparams);


            }catch (\Magento\Framework\Exception\LocalizedException $e) {
                if ($this->_checkoutSession->getUseNotice(true)) {
                    $this->messageManager->addNotice(
                        $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
                    );
                } else {
                    $messages = array_unique(explode("\n", $e->getMessage()));
                    foreach ($messages as $message) {
                        $this->messageManager->addError(
                            $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
                        );
                    }
                }

            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
                $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            }
            unset($params['product']);


        }
         $this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
         $this->cart->save();
        return true;
    }

}

我已经调试了所有的东西,但迷你购物车价格无法改变。在购物车页面中添加到购物车后显示为零。

请帮助我解决这个问题?

任何帮助都将不胜感激。

由于

1 个答案:

答案 0 :(得分:3)

我已经解决了这个问题。这是我更新的代码。

<?php

namespace Mageniks\Customaddtocart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;

class Addtocart extends Action
{
    protected $_resultPageFactory;
    protected $_storeManager;
    protected $productRepository;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;
    protected $_productloader;
    protected $cartRepository;
    protected $quoteManagement;
    protected $_customerSession;
    protected $quoteFactory;
    public function __construct(Context $context,
                                \Magento\Store\Model\StoreManagerInterface $storeManager,
                                \Magento\Catalog\Model\ProductRepository $productRepository,
                                \Magento\Checkout\Model\Session $checkoutSession,
                                \Magento\Checkout\Model\Cart $cart,
                                PageFactory $resultPageFactory,
                                \Magento\Catalog\Model\ProductFactory $_productloader,
                                \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
                                \Magento\Quote\Api\CartManagementInterface $quoteManagement,
                                \Magento\Customer\Model\Session $customerSession,
                                \Magento\Customer\Model\CustomerFactory $customerFactory,
                                \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
                                \Magento\Quote\Model\QuoteFactory $quoteFactory)
    {
        parent::__construct($context);
        $this->_resultPageFactory = $resultPageFactory;
        $this->productRepository = $productRepository;
        $this->_storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->cart = $cart;
        $this->cartRepository = $cartRepository;
        $this->_productloader = $_productloader;
        $this->quoteManagement = $quoteManagement;
        $this->_customerSession = $customerSession;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->quoteFactory = $quoteFactory;
    }

    protected function addProduct($products)
    {
         // Note : $products peramater contain all product information.
        $quote = $this->_checkoutSession->getQuote();
        foreach($products as $params)
        {
            $cartparams = array();          
           $productId = $this->_objectManager->create('Magento\Catalog\Model\Product')->getIdBySku($params['sku']);     
           $product = $this->_productloader->create()->load($productId);
            if (!$product) {
                return false;
            }
            $cartparams['product'] = $product->getId();            
            $customOptions = $this->_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);

                foreach ($customOptions as $option) 
                {
                    if($option['title'] == "option1")
                    {                       
                            $cartparams['options'][$option['option_id']] = "Color : black";
                    }
                    else if($option['title'] == "option2")
                    {


                            $cartparams['options'][$option['option_id']] = "Color : white";


                    }else
                    {
                        $cartparams['options'][$option['option_id']] = "";
                    }
                }



            if (isset($params['qty'])) {
                $cartparams['qty'] = $params['qty'];
            } else {
                $cartparams['qty'] = 1;
            }
            try {


                $request = new \Magento\Framework\DataObject();
                $request->setData($cartparams);
                $this->cart->addProduct($product,$request);

            }catch (\Magento\Framework\Exception\LocalizedException $e) {
                if ($this->_checkoutSession->getUseNotice(true)) {
                    $this->messageManager->addNotice(
                        $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
                    );
                } else {
                    $messages = array_unique(explode("\n", $e->getMessage()));
                    foreach ($messages as $message) {
                        $this->messageManager->addError(
                            $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
                        );
                    }
                }

            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
                $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            }
            unset($params['product']);


        }
         $this->cart->save();
         $quote->save();
         $quote->collectTotals(); 
         $this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();


        return true;
    }

}

经过这么多谷歌或调试我找到了解决方案。我刚刚更改了设置为dataobject的params中的cart addProduct方法。请查看以下内容。

$request = new \Magento\Framework\DataObject();
$request->setData($cartparams);
$this->cart->addProduct($product,$request);

$ cartparams包含产品数量,自定义选项......等。 $ cartparams传入dataobject,然后将其传递给购物车addProduct方法,它对我有用。