0

I have created an ui component and form. In the form, I have added the country and region fields and in the grid, I need to display the region label instead of the option value. How to achieve this? Please help.

1 Answer 1

1

UI component

<column name="region_id" class="[Vendor]\[Module]\Ui\Component\[Entity]\Listing\Columns\RegionLabel">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">text</item>
                <item name="label" xsi:type="string" translate="true">Region</item>
            </item>
        </argument>
    </column>

Create a custom UI component column in your module. For example, create a file named regionLabel.php

<?php

namespace [Vendor]\[Module]\Ui\Component\[Entity]\Listing\Columns;

use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;

class RegionLabel extends Column
{
    /**
     * @var \Magento\Directory\Model\Region
     */
    protected $regionModel;

    /**
     * RegionLabel constructor.
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param \Magento\Directory\Model\Region $regionModel
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        \Magento\Directory\Model\Region $regionModel,
        array $components = [],
        array $data = []
    ) {
        $this->regionModel = $regionModel;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * Replace region_id value with its label in each row of the grid
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {
                $regionId = $item[$this->getData('name')];
                $region = $this->regionModel->load($regionId);
                $regionLabel = $region->getDefaultName();
                $item[$this->getData('name')] = $regionLabel;
            }
        }

        return $dataSource;
    }
}

I hope it will work for you.

Thanks !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.