I have a little problem because I first add some products into the cart -> this is working. But I also need to change the price of this products I add. The problem about that is, that I only want to change the price for this session. Afterwards the price should be the same as before.
(EDIT) One other idea would be to add a custom temporary discount price but not a discount of coupon code in the controller. Any Idea?
I tried this two solutions already: https://magento.stackexchange.com/a/216111/82120
https://webkul.com/blog/magento2-set-custom-price-of-product/
But none of them did work.
This is my code at the Moment:
Controller.php:
<?php
namespace MassiveArt\ShoppingCart\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class Index extends Action
{
protected $formKey;
protected $checkoutSession;
protected $cart;
protected $product;
public function __construct(
Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
JsonFactory $resultJsonFactory,
FormKey $formKey,
Cart $cart,
Product $product) {
$this->checkoutSession = $checkoutSession;
$this->formKey = $formKey;
$this->resultJsonFactory = $resultJsonFactory;
$this->cart = $cart;
$this->product = $product;
parent::__construct($context);
}
public function execute()
{
try {
$result = $this->resultJsonFactory->create();
$productId = $this->getRequest()->getParam('productId');
$amount = $this->getRequest()->getParam('amount');
$test = $this->getRequest()->getParam('test');
if($test == "set"){
$allItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
foreach ($allItems as $item) {
$itemId = $item->getItemId();
$this->cart->removeItem($itemId);
}
}
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $productId,
'qty' => $amount,
);
$product = $this->product->load($productId);
// Here I want to change the price
$product->save();
$this->cart->addProduct($product, $params);
$this->cart->save();
$result->setData(['message' => __("Product is added in cart")]);
return $result;
} catch(\Exception $e) {
$result->setData(['error' => __($e->getMessage())]);
return $result;
}
}
}
If you need to have any more information to solve this answer, please let me know.