How to add new column in sales_order_grid.xml dynamically or direct from class?
-
14-04-2021 - |
Вопрос
I have created a configuration for selecting fields from sales_order table to join with sales_order_grid table. I need to show these selected extra fields on the sales order listing page. like the screenshot below.
When enabling the fields from configuration it will be shown in the order listing page. Could you please help me to sort out this issue.
I have tried below code in app/code/Vendor/OrderGrid/view/adminhtml/ui_component/sales_order_grid.xmlsales_order_grid.xml
<columns name="sales_order_columns">
<column name="customer_id" class="Venor\OrderGrid\Component\Fields">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
<item name="label" xsi:type="string" translate="true">Customer id</item>
<item name="sortOrder" xsi:type="number">60</item>
<item name="align" xsi:type="string">left</item>
<item name="dataType" xsi:type="string">text</item>
<item name="visible" xsi:type="boolean">false</item>
<item name="filter" xsi:type="string">text</item>
</item>
</argument>
</column>
</columns>
And extend Column class by Fields Vendor\OrderGrid\Component\Fields.
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$item['componentDisabled'] = 1;
$item['visible'] = 0;
}
}
return $dataSource;
}
Решение
You need to add all columns in app/code/Vendor/OrderGrid/view/adminhtml/ui_component/sales_order_grid.xml
Then you need to control the column visibility dynamically. To do that override the 'prepare' method on the Vendor\OrderGrid\Component\Fields.php like below
public function prepare()
{
parent::prepare();
if ($this->canShowColumn()) {
$this->_data['config']['componentDisabled'] = true;
}
}