Many times, the default Magento 2 falls short in the functionalities that are essential for an E-commerce store and hence using the events is a must thing to extend the functionality.
Magento 2 triggers admin_system_config_changed_section event after the save store config action is performed. You may want to use this event to use to get the value from a third party API and throw an error if unmatched. For example, when using the barcode generator to create barcode labels and print them, the barcode library needs to be installed. Otherwise, it throws the error.
However, to throw this error, you need to trigger an event on Magento 2 save store configuration to get the admin configuration value and use the below solution for the same.
Steps to Trigger an Event on Magento 2 Save Store Configuration:
For example, if your system.xml looks something like this:
<section id="meetanshitab" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>General Configuration</label> <field id="name" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Enter Name</label> </field> </group> </section>
Here, the section id is meetanshitab which has to be added in the event name as shown in the below solution:
1. Create event.xml file at app/code/Vendor/Module/etc/adminhtml/events.xml
<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="admin_system_config_changed_section_meetanshitab"> <observer name="custom_admin_system_config_changed_section_meetanshitab" instance="Vendor\Module\Observer\ConfigChange"/> </event> </config>
2. create ConfigChange.php file at app/code/Vendor/Module/Observer/ folder
<?php namespace Vendor\Module\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\Config\Storage\WriterInterface; class ConfigChange implements ObserverInterface { private $request; private $configWriter; public function __construct(RequestInterface $request, WriterInterface $configWriter) { $this->request = $request; $this->configWriter = $configWriter; } public function execute(EventObserver $observer) { $meetParams = $this->request->getParam('groups'); $name = $meetParams['general']['fields']['name']['value']; //to print thatn value in system.log \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info($name); return $this; } } ?>
Hope it helps.
Feel free to share the above solution with fellow developers via social media.
Thanks.