While developing a Magento 2 extension, you have to follow various requirements and one such that I’m posting the solution for is to add a custom button in Magento 2 system configuration.
You would want to create a button in the Magento 2 system configuration for custom functionality or perform an action. For example, call a Helper function or controller action.
I used this solution to create a button that generates a CSV file for product attributes as shown here:
Check the solution below and do let me know how it was useful to you.
Steps to Add Custom Button in Magento 2 System Configuration:
1. Create field in [Vendor]\[Module]\etc\adminhtml\system.xml file
<field id="button_id" translate="label" type="button" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Label Text</label>
<frontend_model>[Vendor]\[Module]\Block\System\Config\Button</frontend_model>
</field>
2. Create Button.php file in [Vendor]\[Module]\Block\System\Config
<?php
namespace [Vendor]\[Module]\Block\System\Config;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Button extends Field
{
protected $_template = '[Vendor]_[Module]::system/config/button.phtml';
public function __construct(Context $context, array $data = [])
{
parent::__construct($context, $data);
}
public function render(AbstractElement $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
protected function _getElementHtml(AbstractElement $element)
{
return $this->_toHtml();
}
public function getCustomUrl()
{
return $this->getUrl('router/controller/action');
}
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->setData(['id' => 'btn_id', 'label' => __('Button Label'),]);
return $button->toHtml();
}
}
3. Create button.phtml file in [Vendor]\[Module]\view\adminhtml\templates\system\config
<?php
$controller = $block->getCustomUrl();
echo $block->getButtonHtml();
?>
That was all about creating a button in system configuration in Magento 2 for custom functionality. To make your extensions work expectedly certain configurations are made to have particular values for that you need to set default values for configuration field in Magento 2.
Feel free to share the above solution with fellow developers.
Thanks.
