Adding a Yes/No Dropdown to Magento 2 Store Configuration

Adding a Yes/No Dropdown to Magento 2 Store Configuration

Most custom modules need a few settings, such as an on/off switch, that admins can change without a developer. Magento 2 builds those screens from your module’s system.xml.

Module files

The example below defines a testimonial module with its own configuration tab, a section, a group and a Yes/No dropdown, plus the ACL and default value files that go with it:

<!----Introduction
Youre Company name = Brush
Your Module name  = Testimonial --->

youre pathe is generate like this
app/code/Brush/Brush/etc/adminhtml/system.xml
app/code/Brush/Brush/Model/Config/Source/ListMode.php



Step 1 
first create system.xml file in following path
--> app/code/YourCompanyname/Modulename/etc/adminhtml/system.xml
-->copy past following code in your system.xml file
  
    <field id="list_mode" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>List Mode</label>
        <source_model>Companyname\Modulename\Model\Config\Source\listmode</source_model>
    </field>
------End step 1 ----------	
------Start Step 2 -------	
After then following Step 2


Create source model file in following path
app\code\Companyname\Modulename\Model\Config\Source\ListMode.php
--> copy past following code in your listmode.php

<?php 
  
namespace Companyname\Modulename\Model\Config\Source;	
class ListMode implements \Magento\Framework\Option\ArrayInterface
    {
    /**
     * {@inheritdoc}
     *
     * @codeCoverageIgnore
     */
    public function toOptionArray()
    {
        return [
            ['value' => 'grid', 'label' => __('Grid Only')],
            ['value' => 'list', 'label' => __('List Only')],
            ['value' => 'Slider', 'label' => __('Slider')],
        ];
    } 
    } 
  
?>

After adding the files, run php bin/magento setup:upgrade and flush the cache. The new tab appears under Stores > Configuration, and you can read the value in code with ScopeConfigInterface.

Stuck on something similar? Our Magento development team is happy to take a look.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.