Creating a custom Field Type

There are certain cases when built-in field types are not enough. Sylius Grids make it easy to define new types.

All you need to do is create your own class implementing FieldTypeInterface and register it as a service.

src/Grid/FieldType.php
<?php

namespace App\Grid\FieldType;

use Sylius\Component\Grid\Definition\Field;
use Sylius\Component\Grid\FieldTypes\FieldTypeInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CustomType implements FieldTypeInterface
{
    public function render(Field $field, $data, array $options = [])
    {
        // Your rendering logic... Use Twig, PHP or even external api...
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'dynamic' => false
            ])
            ->setAllowedTypes([
                'dynamic' => ['boolean']
            ])
        ;
    }

    public function getName(): string
    {
        return 'custom';
    }
}

That is all. Now register your new field type as a service.

config/services.yaml
app.grid_field.custom:
    class: App\Grid\FieldType\CustomType
    tags:
        - { name: sylius.grid_field, type: custom }

Now you can use your new column type in the grid configuration!

config/packages/sylius_grid.yaml
sylius_grid:
    grids:
        app_admin_supplier:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Supplier
            fields:
                name:
                    type: custom
                    label: sylius.ui.name

Last updated