Site icon MageComp Blog

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

img How to Add Button in System Configuration with Custom Action in Magento 2

img How to Add Button in System Configuration with Custom Action in Magento 2

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!

Exit mobile version