product price based on gold price or gold weight in magento 2
-
03-10-2020 - |
Question
Hi guys,
I am a newbie to Magento and i'm Developing a Jewelry store with Magento 2.
In which i need to set product price based on gold price, making charge, gold weight etc. (No fixed prices, price depends on day to day gold price)
In order to get this i need to set a price formula. So my question is
1. Is it possible to calculate price based on product attributes ?
2. If So, how can i do this ?
Please help me to achieve this ?
La solution
Magento 2 provide functionlity to set custom product price before product add to cart, to archive this you need to used event in your extension. Event which is used here is "checkout_cart_save_before" event.
Create file [vendor][Extension]\etc\frontend\event.xml and specify this code for your event.
<event name="checkout_cart_save_before">
<observer name="[Uniqe_event_name]" instance="[vendor]\[Extension]\Observer\AddtocartbeforeObserver" shared="false" />
</event>
Now create a file in [vendor][Extension]\Observer\AddtocartbeforeObserver.php
namespace [vendor]\[Extension]\Observer;
use Magento\Framework\Event\ObserverInterface;
class AddtocartbeforeObserver implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
// Do Your Code Login Here
$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = YOUR_PRICE; //SET YOUR CALCULATED NEW PRICE
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
}
In observer file you get all the detail like options selected by user, product price etc, calculate new price according to logic and set product price show in above example.