This step-by-step tutorial will show you how to use the system.xml
file to add a drop-down field to a Magento 2 module’s system configuration section. Additionally, a unique source model will be developed to provide drop-down alternatives. Let’s get going:
Step 1: Create the System Configuration Field
- Go to
etc/adminhtml/system.xml
in your module to view the file. Make the file if it doesn’t already exist in the proper location. - The XML code for the drop-down field should be added as follows:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="your_section_id" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Your Section Label</label>
<tab>general</tab>
<resource>Vendor_Module::config_section</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>General Settings</label>
<field id="environment" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Environment</label>
<source_model>Vendor\Module\Model\Config\Source\EnvironmentOptions</source_model>
</field>
</group>
</section>
</system>
</config>
XMLYour Section Label
, your_section_id
, and other placeholders should all be replaced with the right values.
Step 2: Create the Source Model
- Create the source model class at Vendor/Module/Model/Config/Source/EnvironmentOptions.php
- To specify the options for the drop-down, add the following PHP code:
<?php
namespace Vendor\Module\Model\Config\Source;
class EnvironmentOptions implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
return [
[
'value' => 'production',
'label' => __('Production')
],
[
'value' => 'sandbox',
'label' => __('Sandbox')
]
];
}
}
PHPStep 3: Clear Cache
Clear the Magento cache using the following command after you’ve implemented the changes:
php bin/magento cache:clean
Step 4: Verify the Result
- To access your Magento admin panel, log in.
- Select
Stores > Configuration
from the menu. - In the left sidebar, under the section you defined (
Your Section Label
), you should see the “General Settings” group and the “Environment”
- In order to test, choose “Production” or “Sandbox” from the drop-down menu, then save the configuration.
Congratulations! In the Magento 2 module system configuration area, you’ve successfully established a drop-down field.
Don’t forget to substitute the specifics of your actual module for placeholders like Vendor
, Module
, section titles
, and routes
. This manual serves as a starting point, and you can further modify it in accordance with your needs.
Very interesting information!Perfect just what I
was searching for!Raise range
Feel free to surf to my page … Bernie O