J'ai essayé de changer le prix de mes produits comme ceci:
Controller.php:
[ÉDITER]
<?php
namespace MassiveArt\ShoppingCart\Controller\Index;
use Magento\Catalog\Model\ProductFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey;
class Index extends Action
{
/**
* @var FormKey
*/
protected $formKey;
/**
* @var Session
*/
protected $checkoutSession;
/**
* @var Cart
*/
protected $cart;
/**
* @var ProductFactory
*/
protected $productFactory;
/**
* Constructor.
*
* @param Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Customer\Model\Session $customerSession
* @param JsonFactory $resultJsonFactory
* @param FormKey $formKey
* @param Cart $cart
* @param ProductFactory $productFactory
*/
public function __construct(
Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Customer\Model\Session $customerSession,
JsonFactory $resultJsonFactory,
FormKey $formKey,
Cart $cart,
ProductFactory $productFactory
) {
$this->checkoutSession = $checkoutSession;
$this->customerSession = $customerSession;
$this->formKey = $formKey;
$this->resultJsonFactory = $resultJsonFactory;
$this->cart = $cart;
$this->productFactory = $productFactory;
parent::__construct($context);
}
public function execute()
{
try {
// Set result data and pass back
$result = $this->resultJsonFactory->create();
$allItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
foreach ($allItems as $item) {
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = 100; //set your price here
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->setSubtotal($price);
$item->getProduct()->setIsSuperMode(true);
}
$this->checkoutSession->setTotalsCollectedFlag(false);
$this->checkoutSession->getQuote()->save();
$this->checkoutSession->getQuote()->setTotalsCollectedFlag(false);
$this->setTotalsCollectedFlag(false);
$result->setData(['message' => __("Products added succesfully")]);
return $result;
} catch (\Exception $e) {
$result->setData(['error' => __($e->getMessage())]);
return $result;
}
}
}
(EDIT) Avec le nouveau code, le prix change, mais pas le sous-total! Comme vous pouvez le voir ici:
Merci d'avance!
quote
du checkoutSession
. Je suis un peu confus.