0

I want to build a custom module to update product title and price in customizable options of a product when the main product details are updated in the magento 2 backend.

as shown in the below image i have SKU 1444 in anothers product customizable options so when i update SKU 1444 price it is not getting reflected in customizable options

Any idea how to do this. Is there a settings in magento backend to do it

1 Answer 1

0

In events.xml observe following event

<event name="catalog_product_save_after">
        <observer name="update_custom_option" instance="Vendor\Module\Observer\UpdateCustomOption" />
    </event>

Observer code

use Magento\Framework\Event\ObserverInterface;
 
class UpdateCustomOption implements ObserverInterface
{
    protected $_cacheTypeList;

    protected $_cacheFrontendPool;
 
    public function __construct( \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
    ) {
        $this->_cacheTypeList = $cacheTypeList;
        $this->_cacheFrontendPool = $cacheFrontendPool;
    }
 
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $sku = $observer->getProduct()->getSku();
        $price = $observer->getProduct()->getPrice();
        $name = $observer->getProduct()->getName(); 
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $CPOptionTypeValue = $resource->getTableName('catalog_product_option_type_value');
        $CPOptionTypePrice = $resource->getTableName('catalog_product_option_type_price');
        $CPOptionTypeTitle = $resource->getTableName('catalog_product_option_type_title');
        $productOptionQuery = "update ".$CPOptionTypeValue ." as t JOIN ".  $CPOptionTypePrice ." as t1 JOIN ". $CPOptionTypeTitle . " as t2 on t.option_type_id = t1.option_type_id && t.option_type_id = t2.option_type_id SET t1.price = ".$price." , t2.title = '".$name."' where t.sku = '".$sku."'";
        $connection->query($productOptionQuery);
        $this->cleanCache();
        } 

    public function cleanCache(){
        $types = array('config','layout','block_html','collections','reflection','db_ddl','eav','config_integration','config_integration_api','full_page','translate','config_webservice');
        foreach ($types as $type) {
                $this->_cacheTypeList->cleanType($type);
                }
        foreach ($this->_cacheFrontendPool as $cacheFrontend) {
                $cacheFrontend->getBackend()->clean();
                }
    }       
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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