Get Free Audit

Creating a Custom Field in Magento 2.0 Module Settings

Sep 1, 2015

1371 Andrei Danilchyk

Creating a Custom Field in Magento 2.0 Module Settings

Very often, to save some module settings we have to create and use custom fields for the module settings page.  To demonstrate the case, let’s take multiselect sorting as an example, which is used in our module BelVG_Priсelist for sorting attributes. We are going to use jQuery UI as a supplementary library, specifically, the part which is responsible for sorting.

In the first place we create a custom field for the module settings in the admin panel.

File app\code\BelVG\Pricelist\etc\adminhtml\system.xml:

Key nodes here are sоurсe_mоdel and frоntend_mоdel and the parameter type in the field node:

  • Sоurсe_mоdel – determines values for multiselect;
  • Frоntend_mоdel – defines the layout of the field;
  • Type – determines the type of the source element which we are going to extend;
  • Source_model – this one is quite simple: here we fetch the required attributes and pass as an array with the method toOptionArray().

Magento Audit

Take your online store to the next level with BelVG Magento Audit

Visit the page

File app\code\BelVG\Pricelist\Model\Config\Source\Attributes.php (DOWNLOAD):


Lets have a closer look at the class frоntend_mоdel. The basic idea is to extend the original element (type = text) and to add additional elements into js code. We will use the same bасkend_mоdel for saving values  – in our case this is ( ).

File app\code\BelVG\Pricelist\Block\System\Config\Form\Field\Attributes.php (DOWNLOAD):

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


migration to magento 2

Magento 2 Migration

Take your online store to the next level with BelVG Magento 2 Migration

Visit the page

Basically, it is enough to override only the method _getElementHtml() in our case. But for more complex custom fields you may need to override some other methods too. To connect an additional js library it should be added to requirejs-config.js under app/code/BelVG/Pricelist/view/аdminhtml:

File app/code/BelVG/Pricelist/view/adminhtml/requirejs-config.js:


Also place the library file into the folder: app/code/BelVG/Pricelist/view/adminhtml/web/jqueryext/ui/1.11.4/ jquery-ui.js

So now we have a custom element where you can select and sort elements (in the demonstrated case these are attributes):

55652-clip-80kb

It is possible to use this element in any project or module practically unchanged.

Magento store.belvg.com

Magento Extensions

Take your online store to the next level with BelVG Magento extensions

Visit the store
Andrey Dubina
Partner With Us Looking for a partner to grow your business? We are the right company to bring your webstore to success. Talk to Andrey

Post a new comment

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