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

Php Magento 2以编程方式将产品添加到购物车时,迷你购物车产品价格变为零($0.00),php,magento2,Php,Magento2,我已经创建了一个模块,用于以编程方式在循环中使用自定义选项将产品添加到购物车。当我们运行此控制器代码时,它将在购物车页面中显示价格为$0.00的产品,但在迷你购物车中显示价格为$0.00的产品。 我的控制器代码如下所示 <?php namespace Mageniks\Customaddtocart\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Co

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

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

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

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