Bhaveshpp

Professional Magento Developr - Healp eachother to grow

Magento 2: Ui component grid html column

18 Dec 2021 » magento2, ui-component

add column in ui component

<?xml version="1.0" encoding="UTF-8"?>
<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_invoice_columns">
        <column name="tf_synced_at" class="Bhaveshpp\Twinfield\Ui\Component\Listing\Column\TFSync">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">TF sync</item>
                    <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>


Add observer

namespace Bhaveshpp\Twinfield\Ui\Component\Listing\Column;

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

/**
 * Class TFSync
 */
class TFSync extends Column
{

    /**
     * Constructor
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) 
            {
                $value = $item[$this->getData('name')];
                if (stripos($value, '0000') !== false) 
                {
                    $value = null;
                }
                // $item[$this->getData('name')] = ($value ? true : false);
                $item[$this->getData('name')] = sprintf(
                    '<span style="color:rgb(%s)" title="Synced with Clougistic at [%s]">%s</span>', 
                    ($value ? '0,127,0' : '255,0,0'), $value, ($value ? '&check;' : '&cross;')
                );
            }
        }

        return $dataSource;
    }
}


Thanks.