Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 42 ยท Requests and Output

UI Components Overview

Learn how Magento UI components build admin grids and forms from XML, how data providers feed them JSON, and where knockout and jQuery fit in.

Most of the Magento admin is not built from the blocks and PHTML templates you met in Blocks, ViewModels and PHTML Templates. The product grid, the order grid, the customer edit form and the CMS page form are all UI components: a screen is described in an XML file, a PHP data provider supplies the rows, and JavaScript running in the browser draws the result.

This lesson is an overview. UI components are a large subsystem with its own JavaScript framework, so the goal is to give you a map: what the XML files look like, how a grid gets its data, how a form saves it, and which part is PHP, which is XML and which is JavaScript. All real Magento XML and PHP in this lesson is read-only. The runnable examples are plain-PHP stand-ins that reproduce the idea of a data provider and of a form definition, and each section says what is real and what is the stand-in.

The big picture

A UI component page has three cooperating parts.

  1. Definition. An XML file in view/adminhtml/ui_component/ (module-relative). Its root element is listing for grids or form for forms. The file names columns, fields, buttons, filters and the data source.
  2. Data. A PHP data provider class, wired up in the XML. For a grid it returns a page of rows; for a form it returns the values of one record.
  3. Rendering. The UI framework converts the XML into a JSON-like configuration and sends it to the browser together with the data. JavaScript components, built on knockout templates, create the table, the filters, the paging controls and the form inputs.
flowchart LR
    X["ui_component XML<br/>(listing or form)"] --> P["PHP: build component tree"]
    P --> J["JSON configuration<br/>embedded in the page"]
    D["Data provider<br/>(PHP class)"] --> J
    J --> B["Browser: JS components<br/>(knockout templates)"]
    B -->|"AJAX: filters, paging, sorting"| D

The XML describes the screen, the data provider supplies the rows, and the browser asks the provider again whenever the user filters, sorts or pages.

The page itself still comes from a controller and a layout file. A layout handle for an admin page contains a line like this, which pulls in the component by name:

XML
<!-- view/adminhtml/layout/acme_note_note_index.xml (read-only) -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <uiComponent name="acme_note_listing"/>
        </referenceContainer>
    </body>
</page>

The name acme_note_listing must match the file name acme_note_listing.xml in the ui_component folder. Everything else happens inside that file.

A grid (listing)

A listing file has a few standard parts. This is a shortened, typical skeleton, not a complete file.

XML
<!-- view/adminhtml/ui_component/acme_note_listing.xml (read-only, shortened) -->
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">acme_note_listing.acme_note_listing_data_source</item>
        </item>
    </argument>
    <settings>
        <spinner>acme_note_columns</spinner>
        <deps>
            <dep>acme_note_listing.acme_note_listing_data_source</dep>
        </deps>
    </settings>
    <dataSource name="acme_note_listing_data_source" component="Magento_Ui/js/grid/provider">
        <settings>
            <storageConfig>
                <param name="indexField" xsi:type="string">note_id</param>
            </storageConfig>
            <updateUrl path="mui/index/render"/>
        </settings>
        <aclResource>Acme_Note::notes</aclResource>
        <dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider"
                      name="acme_note_listing_data_source">
            <settings>
                <requestFieldName>id</requestFieldName>
                <primaryFieldName>note_id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <listingToolbar name="listing_top">
        <bookmark name="bookmarks"/>
        <columnsControls name="columns_controls"/>
        <filters name="listing_filters"/>
        <paging name="listing_paging"/>
    </listingToolbar>
    <columns name="acme_note_columns">
        <column name="note_id">
            <settings>
                <filter>textRange</filter>
                <label translate="true">ID</label>
                <sorting>desc</sorting>
            </settings>
        </column>
        <column name="title">
            <settings>
                <filter>text</filter>
                <label translate="true">Title</label>
            </settings>
        </column>
    </columns>
</listing>

Read it from the inside out:

  • <columns> lists the columns. Each <column name="..."> must match a field in the rows the data provider returns. The <filter> setting chooses the filter type shown in the filter panel, and <sorting> sets a default sort.
  • <listingToolbar> adds the standard bar: saved views (bookmark), the column chooser, filters and paging. You do not write any of that behaviour.
  • <dataSource> names the source of rows. The component attribute is a JavaScript module, and the <dataProvider> element names the PHP class. The <aclResource> limits who may load data. ACL is covered in Admin Controllers, Menus and ACL.
  • The names inside js_config and <deps> are fully qualified: <component name>.<child name>. Mistyping one is the most common reason a grid shows an endless loading spinner.

Where do the rows come from? For a table in the database, the stock DataProvider class gets a collection through a virtual type declared in di.xml. Virtual types are covered in Virtual Types and Constructor Arguments, and collections in Models, Resource Models and Collections.

XML
<!-- etc/di.xml (read-only, shortened): map the data source name to a collection -->
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <arguments>
        <argument name="collections" xsi:type="array">
            <item name="acme_note_listing_data_source" xsi:type="string">Acme\Note\Model\ResourceModel\Note\Grid\Collection</item>
        </argument>
    </arguments>
</type>

When the browser needs a page of rows it sends the filters, sort order and paging parameters in an AJAX request. The provider applies them to the collection and returns JSON with two keys: items (the rows) and totalRecords (the count for the whole filtered set, so paging knows how many pages exist). The stand-in below does exactly that with an in-memory array.

PHP A stand-in grid data provider

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that totalRecords is 3 even though only two rows were returned: it counts the whole filtered set. In real Magento the same job is done by the database through addFieldToFilter, setOrder and setPageSize, which you will meet in Collections, Filters and SearchCriteria.

A form

A form file uses the root element form. Fields live in <fieldset> elements, and each <field> chooses an input type with the formElement attribute: input, textarea, select, checkbox, date, fileUploader and others exist. Validation rules are declared in XML, and the JavaScript framework checks them in the browser before submitting.

XML
<!-- view/adminhtml/ui_component/acme_note_form.xml (read-only, shortened) -->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <settings>
        <buttons>
            <button name="save" class="Acme\Note\Block\Adminhtml\Note\Edit\SaveButton"/>
        </buttons>
        <namespace>acme_note_form</namespace>
        <dataScope>data</dataScope>
        <deps>
            <dep>acme_note_form.acme_note_form_data_source</dep>
        </deps>
    </settings>
    <dataSource name="acme_note_form_data_source">
        <settings>
            <submitUrl path="acme_note/note/save"/>
        </settings>
        <dataProvider class="Acme\Note\Model\Note\DataProvider" name="acme_note_form_data_source">
            <settings>
                <requestFieldName>note_id</requestFieldName>
                <primaryFieldName>note_id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <fieldset name="general">
        <settings>
            <label translate="true">Note</label>
        </settings>
        <field name="title" formElement="input">
            <settings>
                <dataType>text</dataType>
                <label translate="true">Title</label>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
            </settings>
        </field>
    </fieldset>
</form>

Two things differ from the grid. The <submitUrl> points to an ordinary admin controller that receives the posted values, so saving a form is not magic: it is a controller action like any other (see Routing and Controllers). And the form's data provider extends Magento\Ui\DataProvider\AbstractDataProvider; its getData() returns the record keyed by its ID, so the browser can fill the inputs when you edit an existing item.

The stand-in below treats the form definition as data: an array of fields with rules. It builds the initial values from a record and validates a submitted payload, which is what the browser-side validators do before the request is sent.

PHP A stand-in form definition and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real framework validates in the browser for the user's convenience, but a browser check is never a security boundary. The save controller must validate again on the server.

Knockout, jQuery and the JavaScript side

You will rarely write the JavaScript behind a standard grid or form, but you should recognise the pieces.

  • Components are JavaScript modules loaded by RequireJS. The component attribute in the XML (for example Magento_Ui/js/grid/provider) names the module. A component has observable properties and a .html template, written with knockout bindings such as data-bind="text: label".
  • Registry. Components find each other by their fully qualified names (acme_note_listing.acme_note_listing_data_source). This is why the deps and provider names above must match exactly.
  • jQuery widgets are the older, lower-level mechanism. The storefront uses them heavily (for example for the mini cart and product galleries), and they are attached to ordinary HTML with a data-mage-init attribute or an x-magento-init script tag. UI components are used on the storefront too, for instance in the checkout.
  • Customizing a column or a field usually means changing the XML, adding a PHP modifier or data provider, or pointing component or template to your own JavaScript or knockout template. Patching the core JavaScript files directly is never the right answer.

The JavaScript layer is deep enough to fill its own tutorial, and this track keeps its attention on the PHP and XML side.

Where to put customizations

When you want to change an existing admin screen, work in this order:

  1. Can a configuration change do it? Hide a column in the UI with the column controls, no code needed.
  2. Can you extend the XML? A file with the same name in your module is merged with the original in the same way as layout XML, so you can add a column or a field without copying the core file.
  3. Do you need different data? Use a plugin or modifier on the data provider rather than replacing it.
  4. Only then replace a component or template.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the XML definition of an admin grid live in a module?

    UI component definitions are XML files in view/adminhtml/ui_component/ (or view/frontend/ui_component/ for the storefront). The file name is the name used in the layout's uiComponent element.
  2. 2. What does a grid data provider return to the browser?

    The browser draws the table itself, so the provider returns data. totalRecords counts the full filtered set so the paging control knows how many pages exist.
  3. 3. A grid stays on a loading spinner forever. Which cause is the most likely in a hand-written component?

    Components find each other through the registry by qualified names such as listing_name.data_source_name. A typo means the provider never resolves and the grid waits.
  4. 4. Is browser-side validation declared in a form's XML enough to protect the save?

    Anyone can post to the save URL without using your form, so browser checks are only a convenience. The server must validate every value.

Summary

  • Admin grids and forms are UI components: an XML definition (listing or form), a PHP data provider and browser-side JavaScript.
  • A listing's <columns> must match the keys of the rows the provider returns; items and totalRecords are the two parts of the response.
  • A form posts to a normal controller through <submitUrl>, and its provider returns the record keyed by ID.
  • Components find each other by fully qualified names, so a typo breaks loading.
  • Extend by merging XML, adding modifiers or plugins, and only then replace components or templates.
  • Browser validation is a convenience; always validate on the server.

Next: Declarative Schema (db_schema.xml)