A Magento UI component is a type of user interface element that is used to build custom pages in Magento 2. UI components are responsible for rendering data on the frontend, and are designed to be reusable, flexible and easy to maintain. They provide a way to separate the data presentation and processing, allowing developers to focus on creating custom pages that meet the specific requirements of their projects.
UI components are created using XML and JavaScript, and are composed of several different elements, including:
- The template: defines the structure of the UI component and includes placeholders for the data
- The JavaScript component: handles the data processing and manipulation
- The layout XML: defines the structure of the page, including the placement of the UI components
- The data provider: retrieves the data that will be used to render the UI component
Here is a code example that demonstrates how a UI component can be created in Magento 2:
<!-- layout XML -->
<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="product_list"/>
</referenceContainer>
</body>
</page>
<!-- template -->
<!-- The template is a .phtml file stored in the template folder -->
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: price"></td>
</tr>
</tbody>
</table>
// JavaScript component
define([
'uiComponent',
'Magento_Ui/js/model/messageList',
'jquery',
'ko',
'uiRegistry',
'mage/translate'
], function (Component, globalMessageList, $, ko, registry) {
'use strict';
return Component.extend({
initialize: function () {
this._super();
this.items = ko.observableArray([]);
this.loadData();
},
loadData: function () {
var self = this;
$.ajax({
url: '/product/list',
type: 'GET',
dataType: 'json'
}).done(function (data) {
self.items(data);
});
}
});
});
In this example, the layout XML defines the structure of the page and includes a reference to the UI component named “product_list”. The template defines the structure of the UI component and includes placeholders for the data. The JavaScript component handles the data processing and manipulation, and retrieves the data from the server using an AJAX request.