How to create a grid in back-end Magento 2

This post is not about something new, yet it is still necessary while working with Magento 2: creating a grid in the backend.

I hope this post can be useful to who is struggling with it. Now let’s code!

I assume you all know the way to create module so I will focus on the main stuff. Let’s name our module Test.

To begin with, we need to create a page in backend with 2 files:

  • 1st file: app/code/Magenest/Test/etc/adminhtml/routes.xml with the following content:
  •  2nd file : app/code/Magenest/Test/Controller/Adminhtml/Grid/Index.php with the following content:

The two files above just created a page in backend (with no content of course) and its URL is localhost/magento/admin/test/grid/index.
However, not everyone knows about this URL. Moreover, if the secret keys are enabled for the administrator URLs, it is impossible to build a correct URL due to the lack of the keys.

Hence, at the next step, we should create an extra menu item in Admin menu so that we can easily navigate to our custom page.

Create a file menu.xml in app/code/Magenest/Test/etc/adminhtml with content:

Add the following code to execute method of Index controller:

Then clean the cache and navigate to the admin page, you should see the menu item Grid added under Magenest Test section, like this:

Next, we need to create a table in the database for grid and define model, resource model to collect data.

  •  Create table by adding file InstallSchema.php to app/code/Magenest/Test/Setup with the following content:
  •  Create Test.php in app/code/Magenest/Test/Model :
  •  Create Test.php in app/code/Magenest/Test/Model/ResourceModel :
  •  Create Collection.php in app/code/Magenest/Test/Model/ResourceModel/Test :

Then, we want to send the collection to the grid. To do that, we put the file name di.xml to app/code/Magenest/Test/etc/:

Since we already have a database for the grid, we need to define grid’s block by creating app/code/Magenest/Test/Block/Adminhtml/Grid.php :

For the next step, we will create a list column inside grid block by adding test_grid_listing.xml to app/code/Magenest/Test/view/adminhtml/ui_component:

This code will add different columns such as Product Id, Product name, Contact Name,… to our grid block above.

The next file we need to create is its layout, put the file test_grid_index to app/code/Magenest/Test/view/adminhtml/layout :

Finally, we will define the action for the grid. Let’s create delete and edit action for this.

Add the file GridActions.php to app/code/Magenest/Test/Ui/Component/Listing/Column:

Okay, that’s enough for coding today. Let see our result. Run setup:upgrade, flush the cache and navigate to the Grid page, we should see something like this: