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

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

3 hours ago

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

2 days ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

5 days ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

6 days ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

7 days ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

7 days ago