·

photo credit: tpe10-bloom-f25-l7-1920 via photopin (license)

How to add a custom renderer to the admin grid in Magento 2

Tags:

So you want to add a custom render to the admin grid in Magento 2 huh? Well, today I was faced with just that same task:
One parameter of my custom model was a reference to the manufacturer ID. So the manufacturer ID is stored in the database, but in my grid I wanted to show the name of the manufacturer instead of it’s ID of course. So I needed to add a custom renderer for this column. Lucky for me, achieving this is fairly simple in Magento 2.

Add a renderer to your grid XML

In my grid XML, on the position where I declare the manufacturer column, I added an argument called ‘renderer’. The value of this argument pointed to my custom renderer:

Note the renderer -argument in the example above. Now let’s take a look at …

The renderer class

Let’s break this code down:

  • In the constructor I used dependency injection so I can have access to the registry and the attribute factory (that will help me later on loading the manufacturer attribute).
  • In the _getValue() -method I load the manufacturer-attribute, fetch it’s options, and return the label of the option that matches with my ID.
  • I also make use of the registry so that the $options -array only needs to be loaded once, and used many (which is of course best practice when rendering columns in the grid).

That’s it. Hoped this helps you some…

Visitors give this article an average rating of 3.6 out of 5.

How would you rate this article?

Leave a Reply