Create a Custom Source Model in Configuration
In this post we will continue with the system.xml configuration file in Magento 2 and have a look on the field's option <source_model>. By default, in Magento 2 there are several out of box Source Models that we can use but also we can create our custom one. Let's do it!
A Source Model serves to insert values into certain fields like dropdowns, checkboxes, multiselects, radios in the system configuration Magento admin. So not all fields can have a Source Model. Some of the default Source Models are listed below and are located under the /vendor/magento/module-config/Model/Config/Source/ folder :
- Magento\Config\Model\Config\Source\Locale → Locale options
- Magento\Config\Model\Config\Source\Enabledisable → Enable / Disable options
- Magento\Config\Model\Config\Source\Nooptreq → No / Optional / Required options
- Magento\Config\Model\Config\Source\Store → Store options
- Magento\Config\Model\Config\Source\Website → Website options
- Magento\Config\Model\Config\Source\Yesno → Yes / No options
- Magento\Config\Model\Config\Source\Yesno → Yes / No / Specified options
- Magento\Config\Model\Config\Source\Locale\Country → Country options
- Magento\Config\Model\Config\Source\Locale\Currency → Currency options
- Magento\Config\Model\Config\Source\Locale\Timezone → Timezone options
- Magento\Config\Model\Config\Source\Locale\Weekdaycodes → Week Day Codes options
- Magento\Config\Model\Config\Source\Locale\Weekdays → Week Days options
- Magento\Config\Model\Config\Source\Email\Template → Email Template options
So now we will create our custom Source Model to serve the values that we need. For our example we will use the Namespace MageVision and the Modulename Blog5.
To indicate Source Model for a field, we have to add the tag <source_model> and define the Source Model path in it like:
Then, we create the MageVision\Blog5\Model\Config\Source\Custom Source Model that was specified above: As we can see, the only method we need to define is the toOptionArray() function which returns an array of options as value-label pairs for our dropdown field.
And in Magento admin the dropdown field looks like:
Another interesting example with a custom Source Model which returns all the customers as options for a multiselect field will look like:
And finally, another more interesting example with a custom Source Model which returns all the categories as options for a multiselect field will look like:
The full example as extension can be found here. Feel free to share this post and ask your questions in the comments below.
Till next time!