How To

Magento 2: Trigger an Event on Save Specific System Configuration Section

Hello Magento Friends,

In this Magento 2 tutorial, we will learn How to Trigger an Event on Save Specific System Configuration Section in Magento 2.

Events in Magento 2 serve as hooks or triggers that allow developers to execute custom code at specific points in the application’s workflow. When a particular event occurs, registered observers can capture and respond to it. In the context of system configuration, we can take advantage of events to execute custom logic when a specific section is saved.

In Magento 2, you can trigger an event when saving a specific system configuration section by utilizing observers and events. Let’s find out how exactly you can accomplish it.

Steps to Trigger an Event on Save Specific System Configuration Section in Magento 2:

Step 1: First, we need to create a “system.xml” file at the following path.

app\code\Vendor\Extension\etc\adminhtml\

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
  <system>
    <tab id="vendor" translate="label" sortOrder="100">
            <label><![CDATA[Custom Setting]]></label>
    </tab>
    <section id="generalsetting" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
      <label>General setting</label>
      <tab>vendor</tab>
      <resource>Vendor_Extension::generalconfig</resource>
       <group id="access_token" translate="label" sortOrder="50" type="text" showInDefault="1" showInWebsite="1" showInStore="1">
              <label>Access Token</label>
              <field id="token" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Access Token </label>
              </field>
        </group>
    </section>
  </system>
</config>

Step 2: After that, we need to create an “events.xml” file at the following path.

app\code\Vendor\Extension\etc\adminhtml\

Then add the code as given below

Note – In the below event, replace section id “generalsetting” with your section id.

<?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_generalsetting">
        <observer name="admin_system_config_changed_section_general_setting" instance="Vendor\Extension\Observer\Triggerconfig"/>
    </event>
</config>

Step 3: After that, we need to create an Observer “Triggerconfig.php” file at the following path.

app\code\Vendor\Extension\Observer\

Now add the below-mentioned code

<?php
namespace Vendor\Extension\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 Triggerconfig implements ObserverInterface
{
    private $request;
    private $configWriter;

    public function __construct(
        RequestInterface $request, 
        WriterInterface $configWriter
    ){
        $this->request = $request;
        $this->configWriter = $configWriter;
    }
    public function execute(EventObserver $observer)
    {
        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/config-save.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);
        $logger->info('trigger system configuration tab');

        $params = $this->request->getParam('groups');
        $token = $params['access_token']['fields']['token']['value'];
        /*Replace your section group name and field name to get values*/        $logger->info('token : '.$token);

        return $this;
    }
}
?>

Step 4: Once all files are created in your Magento, you need to run Magento upgrade, compile and deploy commands as follows.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush

Output:

Once you save the system configuration event will be triggered to generate a log file and you can customize our blog code as per your requirement.

Save System Configuration

Log File

Conclusion:

By harnessing the power of events in Magento 2, you can seamlessly integrate custom logic into the system configuration saving process. Use the above steps to Trigger an Event on Save Specific System Configuration Section in Magento 2.

For any doubts, feel free to connect with me through the comment section. For any customization requirements, Hire Experienced Magento Developers.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago