How to customize Sylius Grids?
How can I customize an existing Sylius Grid? That's a question that I got asked recently and decided to write about my learnings.
In many cases, the default grid configuration might not fully meet your requirements. This is where customization comes into play.
While Sylius provides a YAML configuration approach for customizing grids, I prefer using PHP event listeners for their flexibility. With event listeners, you can use conditions to show or hide fields or actions, making your customizations more dynamic.
Let's create an event listener class to add a new field to the Admin Customer Grid. Here's an example implementation:
<?php
declare(strict_types=1);
namespace App\Grid\Admin;
use Sylius\Component\Grid\Definition\Field;
use Sylius\Component\Grid\Definition\Filter;
use Sylius\Component\Grid\Event\GridDefinitionConverterEvent;
final class CustomerGridListener
{
public function editFields(GridDefinitionConverterEvent $event): void
{
// get the grid instance
$grid = $event->getGrid();
// create a new field and add it to the grid
$field = Field::fromNameAndType('my_new_field', 'twig');
$field->setLabel('app.ui.my_new_field');
$field->setPath('.');
$field->setOptions(['template' => 'admin/grid/fields/my_new_field.html.twig']);
$grid->addField($field);
}
}
In this example, we create a new field called my_new_field and add it to the grid using the addField() method.
But how does the event listener know which grid to modify? The answer is service tags.
To make Sylius aware of the event listener and bind it to a specific grid, you need to add a service definition to your services.yaml file:
App\Grid\Admin\CustomerGridListener:
class: App\Grid\Admin\CustomerGridListener
tags:
- { name: kernel.event_listener, event: sylius.grid.admin_customer, method: editFields }
Here, we define the CustomerGridListener service and tag it with the kernel.event_listener tag. We also specify the grid name sylius.grid.admin_customer and the method to call editFields().
Customizing Sylius grids using PHP event listeners provides a flexible and powerful way to tailor your grids to your specific needs. By following this approach, you can add custom columns, filters, and actions to your grids, making them more useful and user-friendly.
