Calculating Product Prices Based on Configurable Options in Magento
In Magento, configurable products allow you to offer multiple variations of a single product. However, by default, the price for these options isn’t customizable before adding them to the cart. This guide will show you how to modify the price based on selected attributes before a customer adds a product to their cart.
Understanding the Scenario
Let’s say you’re selling custom-made furniture where the dimensions (length and width) affect the final price. You want to calculate the price while displaying the product in the catalog, not just during checkout after adding it to the cart.
To achieve this, we’ll use an event observer that triggers before a product is added to the cart.
Setting Up the Event Observer
The catalog_product_prepare_totals event occurs when a customer is about to add a configurable product to their cart. This is where we can intercept the process and modify prices based on selected options.
First, make sure you have your observer class set up correctly:
use Magento\Framework\Event\ObserverInterface;
class PriceModifier implements ObserverInterface
{
public function execute(Observer $observer)
{
// Your custom price modification logic here
}
}
In the execute method, we can access the quote item being added to the cart and modify its price.
Modifying the Price Based on Selected Options
To access the selected options for a configurable product, we need to retrieve them from the quote item:
$quoteItem = $observer->getQuoteItem();
$parentId = $quoteItem->getProduct()->getParentId();
$childSku = $quoteItem->getSku();
$childProduct = $this->_productRepository->get($childSku);
$selectedOptions = $childProduct->getCustomOption('options');
if ($selectedOptions) {
// The selected options are stored as a serialized array
$optionsArray = unserialize($selectedOptions->value());
}
Assuming your product has length and width as configurable attributes, you can access their values like this:
$length = $optionsArray['info_buyRequest']['length'];
$width = $optionsArray['info_buyRequest']['width'];
$rrp = $childProduct->getPrice();
$finalPrice = $rrp + ($length * $width);
Now, update the quote item’s price:
$quoteItem->setTotal($finalPrice)->save();
Conclusion
By following this approach, you can effectively modify the price of a configurable product before it is added to the cart. This allows you to provide customers with an accurate price estimate during their browsing experience.
Remember to replace PriceModifier with your actual observer class name and ensure that your custom module is enabled in Magento’s configuration.
Visit Laravel Company for more advanced Magento tutorials on event observers and custom pricing logic.