2

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 ?

2
  • Can you specify, for which point you need to help? So everyone give suggestion or answer. Update your question to specific problem or help you need. – Dhiren Vasoya Sep 28 '16 at 6:08
  • Edited my question for more clarity – Shiyas Pathiyassery Oct 3 '16 at 9:50
4

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.

2
  • Thanks for helping me. Let me try with your suggession. But let me ask you one thing, How can i access product attribute values in this observer – Shiyas Pathiyassery Oct 5 '16 at 5:23
  • You can access detail with the used of object $item. – Dhiren Vasoya Oct 5 '16 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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