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.

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

Last updated