How to Add Custom System Configuration Elements in Magento 2.0

Jul 5, 2016715Artsem Miklashevich
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.

Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Vlad

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.

Partner With Us Looking for a partner that will help you to grow your business? We are the right company to develop your webstore. Feel free to get in touch with us. We will be happy to discuss your business opportunities and provide you with a Free Quote. Talk to Vlad

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *