How to Add Custom System Configuration Elements in Magento 2.0

How to Add Custom System Configuration Elements in Magento 2.0

Sometimes module requires to add some custom control elements into the configuration section, like shown on the image below:

How to Add Custom System Configuration Elements in Magento 2.0

Here is how it’s possible to acheive in Magento 2. We need to create the element <frontend_model> for the required attribute in the file app/MyCompany/MyModyle/etc/adminhtml/system.xml. This tag will define our custom field. The block should be extended from the class \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray

In order to customize the field we should update the _construct() method of the block MyCompany\MyModule\Block\Customerfield:

Once the fields have been added, you will get the following form:

How to Add Custom System Configuration Elements in Magento 2.0

But rendering is only the first step. To save the form, we need to collect user input and send it to the backend. Here we should use the Magento\Config\Model\Config\Backend\Serialized\ArraySerialized class to serialize data before saving.

Also we should specify the <backend_model> class to be used for processing and saving serialized data. Backend model is also defined in the system.xml file.

So now the data of the form will be serialized when saved.

To use the form data in the module we need to implement the unserialization task:

This way the array of the form data is transmitted into the fields variable.

In this example I have described only the simplest way of customizing fields. But there are also other more interesting ways that let you set up and display different fields. Let’s check the method Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray::addColumn(), that is used for adding new fields:

As seen from the method, it is possible not only to define the style but also the size of fields and even the use of your own blocks for rendering.

As you see, Magento 2 offers a very convenient and flexible tool for creation and changing form elements in the system configuration section.



Post a new comment

top