Magento – Magento2 UI-Component listing datasource other than DB

adminhtmlmagento2tableuicomponent

I am creating an admin module. I have implemented a section where using a listing ui-component, i present some data from DB to the user.

I want to create a table using the same css style with the listing but this time i want my data to be loaded from a simple array.(possibly from a simple block class???)

My main concern is the style of the table. I want to use the same theme.

Best Answer

With ui components you just add another column and specify the class where your array is returned, i.e:

<actionsColumn name="Rerun" class="Vendor\Module\Ui\Component\Listing\Column\MyArray">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="indexField" xsi:type="string">id</item>
            <item name="urlEntityParamName" xsi:type="string">id</item>
        </item>
    </argument>
</actionsColumn>

and in Vendor\Module\Ui\Component\Listing\Column\MyArray.php you extend from Magento\Ui\Component\Listing\Columns\Column and return your array inside prepareDataSource method:

class MyArray extends Column
{


    /**
     * URL builder
     *
     * @var \Magento\Framework\UrlInterface
     */
    public $_urlBuilder;
    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param UrlInterface $urlBuilder
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $urlBuilder,
        array $components = [],
        array $data = []
    ) {
        $this->_urlBuilder = $urlBuilder;
        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) {
                ...
            }
        }
        return $dataSource;
    }
}