Add select/dropdown in a Magento 2 UI component admin grid
Please check our previous article to add an image column to your admin grid.
If you've worked with
admin grids in Magento 1 or Magento 2, you've likely used the select
field type. This column type displays a label corresponding to the raw value stored in the database. It's commonly used for fields like Yes/No, Active/Inactive, or
lists such as country selections.
However, the values stored in the database are usually raw and meaningful only to developers. For example, a Yes/No field might store 0
for "No" and 1
for "Yes". Without any
customization, your grid will display these raw values (e.g., 0
or 1
), which can be confusing or unintuitive for admin users.
To address this, Magento provides a special UI component:
Magento_Ui/js/grid/columns/select
. This component ensures that the label associated with the stored value is displayed in the grid instead of the raw value.
How to Use
Magento_Ui/js/grid/columns/select
in Admin Grid
In your ui_component/*_listing.xml
file, within the <columns>...</columns>
section, define the column like
this:
<column name="status" component="Magento_Ui/js/grid/columns/select">
<settings>
<label translate="true">Status</label>
<options class="{Namespace}\{Module}\Model\Config\Source\Status"/>
<filter>select</filter>
<dataType>select</dataType>
</settings>
</column>
In this example:
- The column is named
status
. - It uses the
Magento_Ui/js/grid/columns/select
component to render the label. - The
<options>
node specifies the class responsible for providing the value-label pairs.
You can use Magento’s built-in source classes or define your own. Below is an example of a custom source class.
Creating a Custom Options Source Class
Create a class that implements Magento\Framework\Option\ArrayInterface
:
<?php
namespace {Namespace}\{Module}\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
class Status implements ArrayInterface
{
public function toOptionArray()
{
$result = [];
foreach ($this->getOptions() as $value => $label) {
$result[] = [
'value' => $value,
'label' => $label,
];
}
return $result;
}
public function getOptions()
{
return [
'active' => __('Active'),
'inactive' => __('Inactive'),
'pending' => __('Pending'),
];
}
}
getOptions()
returns an associative array ofvalue => label
pairs.toOptionArray()
transforms this into an array of arrays, each containingvalue
andlabel
keys — the format Magento expects.
Final Result
With this setup,
the admin grid will now display user-friendly labels (e.g., "Active", "Inactive", "Pending") instead of raw values like active
, inactive
, or pending
.
This greatly improves the clarity and usability of your Magento admin UI.