A lot of our users ask how to add a button in Magento 2 backend configuration section and call a simple PHP method when clicking on it.

In fact, that’s quite easy to do.

I’ll describe the solution on the example of our new free Others Also Bought extension for Magento 2, where MageWorx – is a vendor’s name and AlsoBought – is a name of the extension.

First, you need to add a button as a field in the Configuration file (mageworx_collect as an example):

To draw this field-button, I use the frontend MageWorx\AlsoBought\Block\System\Config\Collect model. This is how to create it:

This is a typical field model. The button is drawn using the getButtonHtml() method.

To get a URL, you need to use the getAjaxUrl() method.

Next, you will need to create a template:

Note that in this case, you will have to rewrite a part of the code according to your needs. Below is an example of how you can do that.

The AJAX request method onCreate and onSuccess should suit your needs. Also, you can remove the <span class="collect-indicator" id="collect_span"> element. We use it to display the loading (spinner) process and the result of the action.

Also, you will need a controller (where all further operations will be processed) and a router.

That’s basically it.

As I mentioned above, this is a working example from our MageWorx Others Also Bought module for Magento 2.  If you want to further explore it, you can download it from here for FREE.

Should you have any questions on the topic, feel free to drop me a line in the comments below.