Magento 2 - Drop down select list for custom magento system configuration section
Try this code.
system.xml
<field id="list_mode" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>List Mode</label>
<source_model>Vendor\Module\Model\Config\Source\ListMode</source_model>
</field>
Vendor\Module\Model\Config\Source\ListMode.php
namespace Vendor\Module\Model\Config\Source;
class ListMode implements \Magento\Framework\Data\OptionSourceInterface
{
public function toOptionArray()
{
return [
['value' => 'grid', 'label' => __('Grid Only')],
['value' => 'list', 'label' => __('List Only')],
['value' => 'grid-list', 'label' => __('Grid (default) / List')],
['value' => 'list-grid', 'label' => __('List (default) / Grid')]
];
}
}
I got solution. Below line of code will work fine.
System.xml
<field id="select" translate="label" type="select"
sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Select Option</label>
<source_model>Vendor\Modulename\Model\Config\Source\Products</source_model>
</field>
Model file
Vendor\Modulename\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
class Products implements ArrayInterface
{
/*
* Option getter
* @return array
*/
public function toOptionArray()
{
$arr = $this->toArray();
$ret = [];
foreach ($arr as $key => $value) {
$ret[] = [
'value' => $key,
'label' => $value
];
}
return $ret;
}
/*
* Get options in "key-value" format
* @return array
*/
public function toArray()
{
$choose = [
'1' => 'A',
'2' => 'B',
'3' => 'C',
'4' => 'D'
];
return $choose;
}
}
As Magento\Framework\Option\ArrayInterface has been deprecated since v.102.0.1, I'm posting it in the current standard adopted by Magento (I'm using 2.3.3 and PHP 7.3):
<?php
namespace Vendor\Package\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
/**
* Class Profile
* @package Vendor\Package\Model\Config\Source
*/
class Profile implements OptionSourceInterface
{
/**
* @return array
*/
public function toOptionArray() : array
{
return [
['value' => '', 'label' => __('-- Select an Option --')],
['value' => 'grid', 'label' => __('Grid Only')],
['value' => 'list', 'label' => __('List Only')],
['value' => 'grid-list', 'label' => __('Grid (default) / List')],
['value' => 'list-grid', 'label' => __('List (default) / Grid')]
];
}
}