cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2: Set custom discount price to existing cart/quote in controller

Magento 2: Set custom discount price to existing cart/quote in controller

I would like to set a custom discount price to an existing cart/quote in my controller.

 

To give you an example, if the customer clicks a button in the cart he will get a random discount price. But now how can I achieve to add this specific disount price to the cart and quote in the controller?

 

If you need any more information please let me know, the problem for me is, that i just did't find any solution that worked with a controller.

 

This is my code in the current controller:

<?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();

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

            //Delete Current Items:
            $allItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
            foreach ($allItems as $item) {
                $itemId = $item->getItemId();
                $this->cart->removeItem($itemId);
            }

            // Get parameters
            $productIds = $this->getRequest()->getParam('productIds');
            $amounts = $this->getRequest()->getParam('amounts');

            for ($i = 0; $i < count($productIds); $i++) {// Load product by ID
                $product = $this->productFactory->create()->load($productIds[$i]);
                // New product params
                $params = [
                    'form_key' => $this->formKey->getFormKey(),
                    'product'  => $productIds[$i],
                    'qty'      => $amounts[$i],
                ];

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

                // Add product to cart
                $this->cart->addProduct($product, $params);
            }

            //Save cart
            $this->cart->save();

            $result->setData(['message' => __("Products added succesfully")]);

            return $result;
        } catch (\Exception $e) {
            $result->setData(['error' => __($e->getMessage())]);
            return $result;
        }
    }
}

 

As you can see I am currently loading some products into the cart, but now I also need to set a custom discount price after adding the products.

 

I would appreciate if you could help me with this question.

 

3 REPLIES 3

Re: Magento 2: Set custom discount price to existing cart/quote in controller

you can simply call setCustomPrice and setOriginalCustomPrice on each quote item

Re: Magento 2: Set custom discount price to existing cart/quote in controller

Thanks for your answer, but I think I tried it once before and it didn't work. Could you be more specific as it could be an failure on my part. It could be that I apply your answer wrong into my code.

 

I tried it like this:

$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->save();
            }

Re: Magento 2: Set custom discount price to existing cart/quote in controller

How can we do it using events and observer in magento 2 ?