Categories: How ToMagento 2

How to Add a Button in Magento 2 Stores Configuration with Custom Action

Nowadays, Magento is leading the E-commerce CMS just because of the vast community of Magento Developers. Magento 2 comes with tons of rich helpful features and extensible code functionality that helps Business store owner acquire Magento without any hassle. Stepping into Magento 2 by creating first “Hello World” module, Magento developers are always playing with code and create new extensions those help store to kick off the competition. Magento 2 admin’s stores configuration section plays an important role while creating settings for your module.

A lot of our users ask us to come up with solution on creating a button in Magento 2 stores configuration section, where the button can be used to launch different event actions for an extension. We usually call some controller via Ajax and return the result.
Seems difficult, but it is quite easy, simply follow these steps.

Firstly, you need to add button as a field in “System.xml” configuration file by adding below code to app\code\Vendor\Extension\etc\adminhtml\

<pre class="lang:default decode:true">
<?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="tabid" translate="label" sortOrder="1000">
        <label>Extensions</label>
    </tab>
    <section id="sync" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>Sync</label>
        <tab>tabname</tab>
        <resource>[your resource name]</resource>
        <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Configuration</label>
            <field id="build_indexes" translate="label comment tooltip" type="button" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="0">
                <label>Build Search Indexes</label>
                <frontend_model>Vendor\Extension\Block\System\Config\Button</frontend_model>
            </field>
        </group>
    </section>
</system>
</config>
</pre>

Now, you need to create another file “Button.php” file at app\code\Vendor\Extension\Block\System\Config\ using below code.

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Block\System\Config;
class Button extends \Magento\Config\Block\System\Config\Form\Field
{
     protected $_template = 'Vendor_Extension::system/config/button.phtml';

     public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

     public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }
       protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        return $this->_toHtml();
    }
    public function getAjaxUrl()
    {
        return $this->getUrl(‘your action Url’);
    }
    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData(
            [
                'id' => 'btnid',
                'label' => __('Button_Name'),
            ]
        );

        return $button->toHtml();
    }
}
</pre>

Now, you need to create another “<strong>button.php</strong>” file using following code at <strong>app\code\Vendor\Extension\controller\Adminhtml\System\Config\</strong>. So, whenever button is clicked, it will call the action using ajax available in this file.

<pre class="lang:default decode:true">
<?php
namespace Vendor\Extension\Controller\Adminhtml\System\Config;

use \Magento\Catalog\Model\Product\Visibility;

class Button extends \Magento\Backend\App\Action
{
    protected $_logger;
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_logger = $logger;
        parent::__construct($context);
    }
    public function execute()
    {
        $this->_logger->debug('Sync Starts!!');
        // Code to perform specific action    }
}
</pre>

Lastly, we need to create “Button.phtml” file at app\code\Vendor\Extension\view\adminhtml\templates\system\config\ to draw button using following code.

<pre class="lang:default decode:true">
<script>
require([
    'jquery',
    'prototype',
], function(jQuery){
    function function_name() {
        params = {
        };

        new Ajax.Request('<?php echo $block->getAjaxUrl() ?>', {
            loaderArea:     false,
            asynchronous:   true,
            parameters:     params,
            onSuccess: function(transport) {
                var response = JSON.parse(transport.responseText);
            }
        });
    }

    jQuery('#btnid').click(function () {
        function_name ();
    });
});
</script>

<?php echo $block->getButtonHtml() ?>
</pre>

That’s, it. Whenever the button is clicked, it triggers an ajax request to the controller where we can process something and lastly return the result.

Feel free to drop me a line in the comments below & don’t forget to hit the stars if this code works for you.

Happy Coding!

Click to rate this post!
[Total: 19 Average: 3.8]
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

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

2 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

2 days ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

3 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

5 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We're thrilled to announce the release of Hyvä Themes 1.3.6 and 1.3.7! These latest updates…

5 days ago

How Modern E-Commerce Platforms Leverage Docker & Kubernetes for Scalability

Your e-commerce platform is surging - orders are rolling in, traffic spikes are becoming the…

6 days ago