0

I have tried to set a custom price for this purpose but it's getting multiplied by quantity. All I need to add an extra amount(like 50$) to each quote item after it's added to the cart. So it will be like this if have 2 products in the cart... First product Price 5.00$ qty is 10. Second Product Price 3.50$ qty is 20.

I want the calculation be like : (5.00 * 10 + 50) + (3.50 * 20 + 50) item 1 subtotal = 100. item 2 subtotal = 120. Total = 220.

For Magento 1 it was implemented in Sales_Quote_Item model in CalcRowTotal(). like this.. $baseTotal = $this->getBaseRowTotal() + $additionalCharges;

    $baseTotal = $this->getBaseRowTotal() + $additionalCharges; //$additionalCharges is the custom value that i want to add.
    $total = $this->getStore()->convertPrice($baseTotal);
    $this->setRowTotal($this->getStore()->roundPrice($total));
    $this->setBaseRowTotal($this->getStore()->roundPrice($baseTotal));

But in Magento 2 this is not working. Can anyone help ??

1 Answer 1

0

You can achieve this by using registry and observer, check below code

You have to override cart/add controller

\Magento\Checkout\Controller\Cart\Add

You can pass your formatted price in observer like below,

$baseTotal = $this->getBaseRowTotal() + $additionalCharges;

$this->_registry->register('price_values', $baseTotal);

Above is my code, you have to set your logic there.

And now we will use this registry in observer like below,

public function execute(\Magento\Framework\Event\Observer $observer)
{                           
    $items=$observer->getItems();        
    if($items){
        foreach($items as $item){                    
                if($customPrice=$this->registry->registry('price_values')){ 
                    $item->setCustomPrice($customPrice);
                    $item->setOriginalCustomPrice($customPrice);
                    $item->setPrice(null);
                    $item->setBasePrice(null);                        
                    $this->registry->unregister('price_value');
                }                 
            }                
        }
} 

Please check with above technique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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