【问题标题】:Magento 2 When Adding a product to cart programmatically , mini cart product price become zero($0.00)Magento 2 以编程方式将产品添加到购物车时,迷你购物车产品价格为零(0.00 美元)
【发布时间】:2018-05-01 05:22:17
【问题描述】:

我创建了一个模块,用于以编程方式在循环中使用自定义选项将产品添加到购物车。当我们运行此控制器代码时,它会在购物车页面中显示产品价格,但在迷你购物车中显示产品价格为 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;
    }

}

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

你能帮我解决这个问题吗?

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: php magento2


    【解决方案1】:

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

    <?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;
        }
    
    }
    

    经过这么多的谷歌或调试,我找到了解决方案。我刚刚更改了设置为数据对象的参数中的购物车 addProduct 方法。请在下方查看。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多