How To Create Input Tag With Disabled Attribute In Magento 2 system.xml

In the previous blog, I posted the solution to create input tag with disabled attribute in Magento system.xml

This solution is supposed to be implemented when you want to restrict the admin to change the values of particular fields for the proper working of your Magento 2 extensions.

Again, I’ve come up with a similar solution but for Magento 2.

Create input tag with disabled attribute in Magento 2 system.xml and restrict the admin users from changing the values of fields like passwords, API integration key and its details, etc.

Method To Create Input Tag With Disabled Attribute In Magento 2 system.xml:

Find if the field code in system.xml is as below:

<field id="token" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
      <label>Auth Token</label>
</field>

and replace it with below code:

<field id="token" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
      <label>Auth Token</label>
      <frontend_model>Vendor\Extension\Block\System\Config\Form\Field\Disable</frontend_model>
</field>

Create a new file Disable.php at Vendor\Extension\Block\System\Config\Form  folder

<?php
namespace Vendor\Extension\Block\System\Config\Form\Field;

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

class Disable extends Field
{    
    protected function _getElementHtml(AbstractElement $element)
    {
        $element->setDisabled('disabled');
        return $element->getElementHtml();

    }
}

That was all.

Do not let any user play with your configuration! Give them access to only the selected fields. Disable the rest of them with the above solution.

Do share the solution with fellow developers via social media.

Thank you!

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...