As we are aware of Magento 2 store configurations, Those are the heart of our Magento 2 system. Today we are going to see how we can add custom MultiSelect options in-store configurations using system.xml in Magento 2.
Due to Magento 2’s lovely architecture, We’re also able to add our custom configuration in our custom extension as per our custom requirements.
Before starting this tutorial, I’m assuming that you have already created your custom module.
If you don’t have it or don’t know how to create it then check out our other article How To Create a Magento 2 Module.
Step 1: Create system.xml at app/code/Jigar/CustomModule/etc/adminhtml and paste the below code. You can change the code as per your requirement.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<field id="multiselect" translate="label" type="multiselect" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Select Fields</label>
<source_model>Jigar\CustomModule\Model\Config\Options</source_model>
<validate>validate-select</validate>
</field>
</system>
</config>
As you can see in the above example, in our field we have used our custom source_model
for displaying custom select options in the multi-select field.
Step 2: Create Options.php file at app/code/Jigar/CustomModule/Model/Config/ folder to create the model file and paste the below code.
<?php
namespace Jigar\CustomModule\Model\Config;
use Magento\Framework\Data\OptionSourceInterface;
class Options implements OptionSourceInterface
{
const CUSTOMER_NAME = 'name';
const CUSTOMER_EMAIL = 'email';
const CUSTOMER_PHONE = 'phone';
/**
* Get options
*
* @return array
*/
public function toOptionArray()
{
$result = [
['value' => self::CUSTOMER_NAME, 'label' => __('Name')],
['value' => self::CUSTOMER_EMAIL, 'label' => __('Email')],
['value' => self::CUSTOMER_PHONE, 'label' => __('Phone Number')]
];
return $result;
}
}
Now, run the below commands.
php bin/magento cache:flush
In the above code, we’ve added some custom options with custom values that we used in the multiselect. You can see it in the below screenshot.
You will also like :
How to Add Custom Select Options on Store Configuration in Magento 2?
That’s it for this tutorial, See you in the next blog. Keep sharing. Keep Coding…!!
Leave a Comment