Magento – Magento2 : Display two table column values in single UI grid column

admingridmagento2uicomponent

I am working on admin custom module. My module table join with customer table.

Now I want to display User Name (customer firstname and lastname) values in single column in my custom module UI grid.

How can it will be done? Any one have idea?

Thanks

Best Answer

Little late on the answer, but hopefully helpful to those that finds this question.

Vendor/Module/view/adminhtml/ui_component/customer_listing.xml

<column name="fullname" class="Vendor\Module\Ui\Component\Listing\Column\FullName">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <!-- You can change this accordingly -->
            <item name="sortable" xsi:type="boolean">false</item>
            <item name="dataType" xsi:type="string">text</item>
            <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
            <item name="label" xsi:type="string" translate="true">Full Name</item>
        </item>
    </argument>
</column>

Vendor/Module/Ui/Component/Listing/Column/Fullname.php

namespace Vendor\Module\Ui\Component\Listing\Column;

class FullName extends \Magento\Ui\Component\Listing\Columns\Column
{
    /**
     * @param \Magento\Framework\View\Element\UiComponent\ContextInterface $context
     * @param \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory
     * @param array $components = []
     * @param array $data = []
     */
    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        array $components = [],
        array $data = []
    ){
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if(isset($dataSource['data']['items'])){
            foreach($dataSource['data']['items'] as &$item){
                $item['fullname'] = $item['firstname'] . ' ' . $item['lastname'];

            }
        }

        return $dataSource;
    }
}

What is going on is that you are looping through all of the records for the grid listing, and applying data to the fullname column of the grid with the data firstname and lastname fields of your model.