Magento 2 – Understanding the `ui_component` Folder

magento2uicomponentviewxml

In addition to containing familiar folders like layout, and templates, a Magento 2 module's view folder also contains a ui_component sub-folder.

view/adminhtml/ui_component

What is this folder for? It seems to have something to do with rendering UIs in the back end, but it's not clear how I, as a Magento module developer, would use the files in this folder. Is this something reserved for core Magento modules that has no functionality exposed for third party developers, or can I use it to re-use Magento UI components and/or create my own UI components? If so, how?

Best Answer

The ui_component directory contains the xml definition of the grid (or form) used in the backend. Within you layout file you can reference to the ui component with:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <update handle="styles"/>
   <body>
       <referenceContainer name="content">
           <uiComponent name="sample_demolist_listing"/>
       </referenceContainer>
   </body>
</page>

This will then load the file: view/adminhtml/ui_component/sample_demolist_listing.xml, here you define (for a grid) what datasource you want to use, what fields available to show, fields that you want to filter on and mass-actions. See https://github.com/Genmato/M2_Sample/blob/7c0c771c4d66f2ea4eec285bfb9f8ad5d1c67999/view/adminhtml/ui_component/sample_demolist_listing.xml (file is a bit to big to include here).

The datasource is that is referenced in the ui_component xml is created thru the di.xml by defining:

<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="sample_demolist_listing_data_source" xsi:type="string">Genmato\Sample\Model\ResourceModel\Demo\Grid\Collection</item>
            </argument>
        </arguments>
    </type>

In this case the collection is used from Model\ResourceModel\Demo\Grid\Collection.

See https://github.com/Genmato/M2_Sample/releases/tag/0.7.6 for usage in your own module.

Related Topic