How To Add Custom Button In System Configurations Magento 2

Written by Jigar Patel

Dec 13, 2021

How To Add Custom Button In System Configurations Magento 2

Adding a custom button in the system configuration is a quite common task when creating a custom module. Quaternary buttons are only after all the buttons hierarchy have been used.

The system.xml is a configuration file that is used to create configuration fields in Magento 2 System Configuration.

Button in System Config can be used to launch different actions of your extension. In our case, the button will call some controller via Ajax and return some results.

Read This: How To Add Split Button on Admin Page in Magento 2

We are already learned how to create a basic module in Magento 2. We need to create module.xml and registration.php file. You can create module.xml and registration.php from this tutorial.

Here we are using Dolphin as Vendor name and InvoiceEmail as the name of a module.  You can change this according to your Vendor and Module name.

Step 1: Create System XML 

Create system config file system.xml in app/code/Dolphin/InvoiceEmail/etc/adminhtml folder with the following code.

<?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="dolphintab" translate="label" sortOrder="100">
            <label>Dolphin</label>
        </tab>
        <section id="datetime" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                 showInStore="1">
            <class>separator-top</class>
            <label>Date Time</label>
            <tab>dolphintab</tab>
            <resource>Dolphin_InvoiceEmail::config_extension</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                   showInStore="1">
                <label>General</label>
                <field id="run" showInDefault="1" showInStore="0" showInWebsite="0" sortOrder="40" translate="label" type="text">
                    <label>Custom Button</label>
                    <frontend_model>Dolphin\InvoiceEmail\Block\Adminhtml\System\Config\Form\Button</frontend_model>
                    <comment/>
                </field>
            </group>
        </section>
    </system>
</config>

Step 2: Create a Block

Create a Button.php file in the app/code/Dolphin/InvoiceEmail/Block/Adminhtml/System/Config/Form folder with the following code.

<?php

namespace Dolphin\InvoiceEmail\Block\Adminhtml\System\Config\Form;

use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Button extends Field
{
    /**
     * @var \Magento\Framework\UrlInterface|null
     */
    protected $_urlBuilder = null;

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

    /**
     * @param AbstractElement $element
     * @return string
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData([
            'id' => 'inventory_button',
            'label' => __('Update Inventory'),
        ])
            ->setDataAttribute(
                ['role' => 'dolphin-update-inventory']
            );

        /** @var \Magento\Backend\Block\Template $block */
        $block = $this->_layout->createBlock('\Dolphin\InvoiceEmail\Block\Adminhtml\System\Config\Form\Button');
        $block->setTemplate('Dolphin_InvoiceEmail::system/config/form/button.phtml')
            ->setChild('button', $button)
            ->setData('select_html', parent::_getElementHtml($element));

        return $block->toHtml();
    }

    public function getAjaxCheckUrl()
    {
        return $this->_urlBuilder->getUrl('updatestock/updatestock/index');
    }
}

$block->setTemplate() set the button template in system config page.

Step 3: Create Template File

Create a button.phtml file in the app/code/Dolphin/InvoiceEmail/view/adminhtml/templates/system/config/form folder with the following code.

<?php
/** @var $block Dolphin\InvoiceEmail\Block\Adminhtml\System\Config\Form\Button */
?>
<?= $block->getChildHtml('button') ?>
<span class="inventory-indicator" id="inventory_span">
    <img class="processing" hidden="hidden" alt="Collecting" style="margin:0 5px"
         src="<?php echo $block->getViewFileUrl('images/process_spinner.gif') ?>"/>
    <img class="inventoryed" hidden="hidden" alt="Collected" style="margin:-3px 5px"
         src="<?php echo $block->getViewFileUrl('images/rule_component_apply.gif') ?>"/>
    <span id="inventory_message_span"></span>
</span>

<script>
    require([
        'jquery',
        'prototype'
    ], function (jQuery) {

        jQuery('#inventory_button').click(function () {
            //alert("here");
            generateinventorybutton();
        });

        function generateinventorybutton() {
            var inventorySpan = jQuery('#inventory_span');
            new Ajax.Request('<?= $block->getAjaxCheckUrl() ?>', {
                method: 'get',
                loaderArea: true,
                asynchronous: true,
                onCreate: function () {
                    inventorySpan.find('.inventoryed').hide();
                    inventorySpan.find('.processing').show();
                    jQuery('#inventory_message_span').text('');
                },
                onSuccess: function (response) {
                    inventorySpan.find('.processing').hide();

                    var resultText = '';
                    if (response.status > 200) {
                        resultText = response.statusText;
                    } else {
                        resultText = 'Success';
                        inventorySpan.find('.inventoryed').show();
                    }
                    jQuery('#inventory_message_span').text(resultText);

                    var json = response.responseJSON;
                    if (typeof json.time != 'undefined') {
                        jQuery('#row_mageworx_alsobought_general_inventory_time').find('.value .time').text(json.time);
                    }
                }
            });
        }

    });
</script>

getAjaxCheckUrl() method return ajax url from Button Block.

Now execute the below command and refresh the page:

[dt_highlight color="" text_color="" bg_color=""]php bin/magento s:up[/dt_highlight]
[dt_highlight color="" text_color="" bg_color=""]php bin/magento c:c[/dt_highlight]

Result :

How To Add Custom Button In System Configurations Magento 2

You check it also in vendor/magento/module-customer/etc/adminhtml/system.xml for the button. Below code check it in the above path. Create frontend_model like this vendor/magento/module-customer/Block/Adminhtml/System/Config/Validatevat.php.

<group id="store_information">
     <field id="validate_vat_number" translate="button_label" sortOrder="62" showInDefault="1" showInWebsite="1" showInStore="0">
           <button_label>Validate VAT Number</button_label>
           <frontend_model>Magento\Customer\Block\Adminhtml\System\Config\Validatevat</frontend_model>
     </field>
</group>

Above path for your reference.

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding this blog, do consider them posting in the Comments section below!

Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP