Monday, December 11, 2017

How to Use Absolute Pricing for Custom Options in Magento 2 programatically


Here is the solution you can apply. It will work even if you have multiple custom options for a product.

create events.xml in the folder 'Namespace/Module/etc/frontend' and use the event 'checkout_cart_product_add_after'

    <?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="checkout_cart_product_add_after">
            <observer name="customproductprice" instance="Namespace\Module\Observer\CustomProductPrice" />
        </event>
    </config>

Create CustomProductPrice.php in Observer folder.

    <?php
        namespace Namespace\Module\Observer;
   
        use Magento\Framework\Event\ObserverInterface;
        use Magento\Framework\App\RequestInterface;
   
        class CustomProductPrice implements ObserverInterface
        {
            protected $_objectManager;
            public function __construct(
                    \Magento\Framework\ObjectManagerInterface $objectManager
                ) {
                    $this->_objectManager = $objectManager;
                }
            public function execute(\Magento\Framework\Event\Observer $observer) {
                $item = $observer->getEvent()->getData('quote_item');       
                $product=$observer->getEvent()->getData('product');
                $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
                $_customOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($product);
                $totalPrice = 0;
                foreach ($_customOptions['options'] as $key => $value) {
                    $customOptions = $this->_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);
                    foreach ($customOptions as $o) {
                        $values = $o->getValues();
                        foreach ($values as $v) {
                            if ($value['option_value'] == $v->getOptionTypeId()) {
                                $totalPrice += $v->getprice(); /* get price of custom option*/
                            }
                         }
                    }
                }
                $item->setCustomPrice($totalPrice);
                $item->setOriginalCustomPrice($totalPrice);
                $item->getProduct()->setIsSuperMode(true);
            }
   
        }

No comments:

Post a Comment