Changing Product Price on Add to Cart in Magento
If you’re looking to modify product prices dynamically when adding items to the cart in Magento, you can achieve this by implementing a custom observer for the saveAfter event of the quote item model. This allows you to apply your price multipliers directly before an item is added to the cart.
Here’s a step-by-step guide on how to do this:
Understanding the Problem
Let’s say you have a product with a base price of $10, and you want to display the following prices based on the quantity being added to the cart:
- 1x: $50
- 2x: $100
- 3x: $150 … and so on.
To accomplish this, we’ll apply a multiplier of 5 to the base price for any quantity added.
Setting Up Your Custom Observer
First, create a custom observer module. For simplicity, let’s call it ChangingPriceOnCart.
In your etc/events.xml file, define the observer configuration:
<?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="sales_quote_item_save_after">
<observer name="change_price_on_cart" instance="ChangingPriceOnCart\Observer\ChangePriceBeforeAddToCart"/>
</event>
</config>
Now, create your observer class ChangePriceBeforeAddToCart.php in Observer:
<?php
namespace ChangingPriceOnCart\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\Quote\Item;
class ChangePriceBeforeAddToCart implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer): void
{
/** @var Item $item */
$item = $observer->getEvent()->getItem();
// Apply your price multiplier logic here
$basePrice = $item->getData('price');
$multiplier = 5; // Define your desired multiplier
if ($multiplier > 0) {
$newPrice = $basePrice * $multiplier;
$item->setOriginalPrice($newPrice);
$item->setPrice($newPrice);
}
}
}
Implementing the Price Multiplier Logic
In our observer method execute, we first retrieve the base price of the item being added to the cart. We then apply the desired multiplier (in this case, 5) and calculate the new price.
Note that we set both original_price and price to ensure compatibility with various price calculations in Magento’s core functionality.
Conclusion
By following these steps, you can successfully modify product prices before they are added to the cart in Magento. This approach allows for dynamic pricing based on quantity, which is particularly useful for promotional scenarios or tiered pricing structures.
Remember to clear your cache and reindex after implementing this solution:
bin/magento cache:flush
bin/magento indexer:reindex
For more advanced customizations in Magento, feel free to explore the extensive documentation and best practices available at Laravel Company’s Magento resources.