I have a custom module with the columns id, order_id & reason
. Now I want to add the reason value in the order grid with the select filter.
Reasons are listed in the other table of the custom module.
If I am using the text field filter then it is working but in the case of the dropdown filter, it is not working properly.
I have used below code:
vendor/module/view/adminhtml/ui_component/sales_order_grid.xml
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<columns name="sales_order_columns">
<column name="cancel_reason">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Vendor\Moduel\Model\Config\Source\Reason</item>
<item name="config" xsi:type="array">
<item name="visible" xsi:type="boolean">true</item>
<item name="filter" xsi:type="string">select</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
<item name="dataType" xsi:type="string">select</item>
<item name="label" xsi:type="string" translate="true">Cancellation Reason</item>
</item>
</argument>
</column>
</columns>
</listing>
Vendor\Moduel\Model\Config\Source\Reason
<?php
namespace Vendor\Module\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
class Reason implements ArrayInterface
{
public function toOptionArray()
{
$result = [];
foreach ($this->getOptions() as $value => $label) {
$result[] = [
'value' => $value,
'label' => $label,
];
}
return $result;
}
public function getOptions() {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('cancelreason_item');
$sql = "Select `reason` FROM " . $tableName;
$rows = $connection->fetchAll($sql);
$result = [];
foreach($rows AS $row){
$result[$row['reason']] = $row['reason'];
}
return $result;
}
}