Create a uiComponent listing (grid) in the magento2 admin
In Magento 2, the admin panel is where administrators manage various aspects of their online store, such as products, customers, orders, and more. To provide a user-friendly and efficient interface, Magento 2 uses UI components, including UI component listings (grids), which offer a flexible way to display and manage data.
Here are a few reasons why UI component listings (grids) are used in the Magento 2 admin:
- Data Presentation: UI component listings present data in a tabular format, allowing administrators to view and navigate through large datasets easily. The grid structure enables sorting, filtering, and pagination, making it convenient to find specific information.
- Customization: UI component listings can be customized to display specific columns, allowing administrators to focus on relevant data. Columns can be added or removed, and their order can be rearranged based on individual requirements.
- User Interaction: UI component listings provide various interactive elements, such as checkboxes, dropdowns, and inline editing, to facilitate efficient data management. Administrators can perform actions like mass updates, inline editing, or deleting multiple records simultaneously.
- Configuration: Magento 2 provides a comprehensive set of options to configure UI component listings. Administrators can define the data source, specify filtering and sorting options, set up column renderers, and control the grid’s behavior through XML or PHP configuration files.
Extensibility:UI component listings in Magento 2 are highly extensible. Developers can customize existing grid functionalities or create entirely new grids to meet specific business needs. This flexibility allows for seamless integration of custom modules and extensions into the admin panel.
Create the controller for the grid magento2
First of all, we will create our magento2 grid which will allow us to view our contacts in the backend. To do this, start by editing the Index action of your Contact controller (/Hikmadh/Mymodule/Controller/Adminhtml/Test/Index.php) like this to load and display your layout:
namespace Hikmadh\Mymodule\Controller\Adminhtml\Test;
class Index extends \Magento\Backend\App\Action
{
/**
* Index action
*
* @return void
*/
public function execute()
{
$this->_view->loadLayout();
$this->_view->renderLayout();
}
}
Create the layout file of the magento2 grid and the uiComponent “listing”
Create the layout file /Hikmadh/Mymodule/view/adminhtml/layout/contacts_test_index.xml Like this :
Here it is told to get uiComponent and put it in the container “content” of our theme. We will give it the name “mymodule_test_listing” (pay attention to the name you give here because we will use it to create the following file). This magento2 uiComponent is as you can imagine our Grid.
So we will define our uiComponent.
Create the/app/code/Hikmadh/Mymodule/view/adminhtml/ui_component/ folder with the following mymodule_test_listing.xml file:
-
- mymodule_test_listing.mymodule_test_listing_data_source
- mymodule_test_listing.mymodule_test_listing_data_source
- mymodule_test_columns
-
-
- add
- Add a new Contact
- primary
- */*/newAction
MymoduleGridDataProvider
mymodule_test_listing_data_source
hikmadh_contacts_id
id
-
- Magento_Ui/js/grid/provider
-
- hikmadh_contacts_id
-
-
- mymodule_test_listing.mymodule_test_listing.listing_top.bookmarks
- current
-
- true
-
- hikmadh_test_listing.hikmadh_test_listing.listing_top.bookmarks
- columns.${ $.index }
- current.${ $.storageConfig.root}
-
- hikmadh_mymodule_id
-
- textRange
- asc
- ID
-
- true
- text
- input
- contact
- name
- Name
- text
-
- true
-
- true
- text
- input
- contact
- email
- Email
- text
-
- true
-
- false
- 107
- hikmadh_contacts_id
This file looks complex but it is not as complex as it seems.It is just a listing tag that contains 4 child tags:
– argument:Here we declare the data_sources to use (which makes the links between your grid and the database) with the tag js_config.We also declare the spinner, that is the name of the tag “columns” that will be used in our grid. We then declare our buttons in the buttons tag with a name, a label, a class and a target url.
– dataSource:Here we define the dataProvider (the object that will fetch our data in database). With a “class” tag to define the name of the object to be used. This object will be defined later in the di.xml (dependency node file). We give a name to our dataSource via the “name” attribute and then we give it the field to use as the id for the grid in the database (“primaryFieldName”) and for the request (“requestFieldName”). We then define in “config” the component to use (here “Magento_Ui/js/grid/provider”) and the identifier in our bdd “indexField” which here has the value “pfay_contacts_id”.
– columns:It was defined above in the “spinner” section of the “argument” section, here it is named listing_columns. This area will allow us to define our columns with the identifier to be used to find oneself, the type of fields and filters to use for the grid, the type of sorting that will be used and a label
In the actionsColumn we defined the class to use to define the buttons to know ContactsActions. Therefore, create the corresponding app/code/Hikmadh/Mymodule/Ui/Component/Listing/Column/ContactsActions.php file:
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) {
$item[$this->getData('name')]['edit'] = [
'href' => $this->urlBuilder->getUrl(
'mymodule/test/edit',
['id' => $item['hikmadh_mymodule_id']]
),
'label' => __('Edit'),
'hidden' => false,
];
$item[$this->getData('name')]['delete'] = [
'href' => $this->urlBuilder->getUrl(
'mymodule/test/delete',
['id' => $item['hikmadh_mymodule_id']]
),
'label' => __('Delete'),
'hidden' => false,
];
}
}
return $dataSource;
}
}
That’s all..for the moment, it was not so complicated..you see 🙂
Then remember that in this file we defined an object called ContactsGridDataProvider, currently it does not correspond to anything so we will declare this object called a dataProvider by defining it in the dependency injection file (di. Xml).
So create the app/code/Hikmadh/Mymodule/etc/di.xml file like this:
Hikmadh\Mymodule\Model\ResourceModel\Mymodel\Collection
MymoduleGirdFilterPool
Hikmadh\Mymodule\Model\ResourceModel\Mymodel\Collection
MymoduleGirdFilterPool
- Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter
- Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter
- Hikmadh\Mymodule\Model\ResourceModel\Mymodel\Collection
hikmadh_mymodule
Hikmadh\Mymodule\Model\ResourceModel\Mymodel
Here it looks like it is complicated but in fact it is very simple:1- We define a virtualType ContactsGridDataProvider, we pass it to the class of our collection Hikmadh\Mymodule\Model\ResourceModel\Mymodel\Collection and we tell magento to use a "filterPool" with the name "MymoduleGirdFilterPool". 2- We define the "MymoduleGirdFilterPool" just declared by passing a item "regular" and a item "fulltext".
3- we create the type contacts_test_listing_data_source that we use above in our XML (be careful to put the same name) and we define that it will use our collection. 4. Create a VirtualType SearchResult, pass it on to our collection, and tell it to use our "hikmadh_mymodule" table and the resourceModel "Hikmadh\Mymodule\Model\ResourceModel\Mymodel" to find out.
Go to your admin interface and you should now see your grid appears.
Add the add button to our magento2 grid
In our listing component (our grid : /app/code/Hikmadh/Mymodule/view/adminhtml/ui_component/mymodule_test_listing.xml) add the following code in argument to add the "add" button of our grid:
-
-
- add
- Add a new contact
- primary
- */*/newAction
It is in the item “buttons” that you will put all your buttons. This element is an “array”, so you can put several items in a row. Each element will be a button, for which you define a name, label, class and url. Which one is redirecting when clicked (here we redirect to */*/add which means that we will redirect To the “Add” action of the same folder as our current Action. We create a file /app/code/Hikmadh/Mymodule/Controller/Adminhtml/Test/Add.php that contains our action:
Reload your page and click on the “Add a new Contact” button that appears now, you should arrive on your action which displays a blank page with “test add”. We’ll see in the next tutorial how to display the form that will add a new contact.
Optional items:
The optional elements are put in the “container”. The “container” is the 4th non-mandatory tag of the listing element after “argument”, “dataSource”, and “columns” which are mandatory. It takes at least one data argument which allows to define its template ( ui/grid/toolbar ). Here’s how to integrate it into our /app/code/Hikmadh/Mymodule/view/adminhtml/ui_component/mymodule_test_listing.xml file
Add the “columns controls” Container
The columns controls is an element that allows you to manage the columns of your grid on the fly, you can add/remove a column/reset the grid to a base state and you can save the grid state in the session.
Here is the code to integrate in the “container” to display the columns controls:
-
-
- mymodule_test_listing.mymodule_test_listing.mymodule_test_columns
- Magento_Ui/js/grid/controls/columns
- dataGridActions
The Bookmarks
The bookmarks allows you to save the state of the listing which you modified with the element “columns_control” previously created. Here is how to integrate the “bookmark” in the “container” :
-
- Magento_Ui/js/grid/controls/bookmarks/bookmarks
- dataGridActions
-
- mymodule_test_listing
Be sure to put the namespace and define your urls.
Pagination
The pagination of the grid under magento2 is super well done and very easy to integrate, it is enough just to pay attention to the 2 paths “provider” and “selectProvider”.
Here is the code to insert:
-
-
- mymodule_test_listing.mymodule_test_listing.listing_top.bookmarks
- current.paging
- mymodule_test_listing.mymodule_test_listing.contacts_test_columns.hikmadh_mymodule_id
- bottom
Magento2 grid filters
To be able to filter the table can sometimes be practical, for that a “filter” element can be added to the magento grid. Here’s how to do it:
-
-
- mymodule_test_listing.mymodule_test_listing.listing_top.bookmarks
- curren.filters
-
- mymodule_test_listing.mymodule_test_listing.listing_top.listing_filters
-
- mymodule_test_listing.mymodule_test_listing.listing_top.bookmarks:current.columns.${ $.index }.visible
By default, it takes all the fields available on the grid, it knows how to filter with the “filter” item of your “columns” like these:
ici type text :
- text
ici type textRange :
- textRange
Mass Actions under magento2
You want to be able to select several lines of your grid to delete them all at once or do another specific processing on all the lines selected at the same time? The Mass Actions are made for this. First of all it will be necessary to add the inputs on the edge of our grid to be able to select the lines, so in “columns” add this before the “column”:
-
- pfay_contacts_id
You now see the checkboxes on the side that allow you to select multiple lines. Here is how to integrate the selectbox which allows to select the action to be performed once we have selected our lines:
-
- mymodule_test_listing.mymodule_test_listing.mymodule_test_columns.ids
- bottom
- hikmadh_mymodule_id
-
- delete
Delete Selected
-
- Delete all selected contacts
- Do you want to delete all the selected contacts?
Here it is the same, we have to be careful on what we enter as a path for the “selectProvider” and we add the actions following each other. In order to prepare the next tutorial, we will create the MassDelete controller. This is where we will be redirected when we select our action (*/*/massDelete). Create the following file /app/code/Hikmadh/Mymodule/Controller/Adminhtml/Test/MassDelete.php :
getRequest()->getParam('selected', []);
if (!is_array($ids) || !count($ids)) {
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index', array('_current' => true));
}
foreach ($ids as $id) {
if ($Mymodel = $this->_objectManager->create(Mymodel::class)->load($id)) {
$Mymodel->delete();
}
}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', count($ids)));
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/index', array('_current' => true));
}
}
Create a search field in admin magento2
To create a search field on the magento admin, you must add an optional element in the container that will be called “filterSearch” like this:In app/code/Hikmadh/Mymodule/view/adminhtml/ui_component/mymodule_test_listing.xml you can add:
-
- mymodule_test_listing.contacts_test_listing_data_source
- mymodule_test_listing.mymodule_test_listing.listing_top.listing_filters_chips
-
- mymodule_test_listing.mymodule_test_listing.listing_top.bookmarks
- current.search
So edit your upgrade file (app/code/Hikmadh/Mymodule/Setup/UpgradeSchema.php) like this:
startSetup();
if (version_compare($context->getVersion(), '0.2.0', '<')) {
$tableName = $setup->getTable('hikmadh_mymodule');
$setup->getConnection()->addColumn($tableName, 'comment', [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 255,
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Comment'
]);
}else if (version_compare($context->getVersion(), '0.3.0', '<')) {
/**
* Add full text index to our table department
*/
$tableName = $setup->getTable('hikmadh_mymodule');
$fullTextIntex = array('name','email'); // Column with fulltext index, you can put multiple fields
$setup->getConnection()->addIndex(
$tableName,
$setup->getIdxName($tableName, $fullTextIntex, \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT),
$fullTextIntex,
\Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
);
}
$setup->endSetup();
}
}
We will see in the next tutorial how to create the create/delete/edit actions and the creation and editing form linked to our grid and our contact object! This is the end of this tutorial on magento2 uiComponent listing, congratulations to you who followed this tutorial until the end. If this tutorial tells you more or you have a question, share this article on twitter and don’t hesitate to let a comment!