2

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.

  • Still searching for an answer that works – Felix Schönherr Aug 21 '19 at 8:55
0

Id recommend using an observer event for this rather than trying to execute it within a controller. with the below code you can hook into the add to cart action and update the product price as it is added to the basket.

VendorName/ModuleName/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="module_customprice" instance="VendorName\ModuleName\Observer\CustomPrice" />
    </event>
</config>

VendorName/ModuleName/Observer/CustomSessionPrice

namespace VendorName\ModuleName\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomSessionPrice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {

        $customer = $observer->getEvent()->getCustomer();
        if(!empty($customer->getId())) {
             $item = $observer->getEvent()->getData('quote_item');          
             $item = ( $item->getParentItem() ? $item->getParentItem() : $item );

             $item->setCustomPrice(100);
             $item->setOriginalCustomPrice(100);
             $item->getProduct()->setIsSuperMode(true);
        }

    }

}

If you wish to do via ajax you will need to amend your code like so

<?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
{
    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var Cart
     */
    protected $cart;

    /**
     * @var Product
     */
    protected $product;

    /**
     * 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 Product $product
     */
    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\Session $customerSession,
        JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->customerSession = $customerSession;
        $this->formKey = $formKey;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
        $this->product = $product;
        parent::__construct($context);
    }

    public function execute()
    {

        try {

            // Set result data and pass back
            $result = $this->resultJsonFactory->create();

            if(!$this->customerSession->getCustomer()->getId()) {
                $result->setData(['error' => __('Invalid session ID')]);
            }

            // Get parameters
            $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);
                }
            }

            // Load product by ID
            $product = $this->product->load($productId);

            // New product params
            $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId,
                'qty'   => $amount,
                'price' => '100'
            );

            // Save Product
            $product->save();

            // Add product to cart and 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;
        }
    }
}
| improve this answer | |
  • Thanks for your answer, but where do i need to add this xml code? – Felix Schönherr Aug 21 '19 at 7:14
  • sorry have updated answer – Dava Gordon Aug 21 '19 at 7:17
  • Thank you very much! – Felix Schönherr Aug 21 '19 at 7:20
  • Sorry to ask, but when is the event getting thrown? – Felix Schönherr Aug 21 '19 at 7:22
  • when you click add to cart this even is fired just before its added to the quote if you add a die to the just before $customer = $observer->getEvent()->getCustomer(); you will be able to see were it is being executed – Dava Gordon Aug 21 '19 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.