Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Grid Bundle Laravel Package

sylius/grid-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require sylius/grid-bundle
    

    Ensure Sylius\Bundle\GridBundle\SyliusGridBundle is registered in config/bundles.php.

  2. First Grid Definition Use the make:grid command to scaffold a grid:

    php bin/console make:grid product
    

    This generates:

    • A YAML/Php configuration file (e.g., config/grids/product.yaml).
    • A service definition for the grid.
  3. Basic Usage in a Controller

    use Sylius\Bundle\GridBundle\Grid\GridFactory;
    
    class ProductController
    {
        public function __construct(private GridFactory $gridFactory) {}
    
        public function index(): Response
        {
            $grid = $this->gridFactory->create('product');
            $grid->load();
    
            return $this->render('product/index.html.twig', [
                'grid' => $grid,
            ]);
        }
    }
    
  4. Render in Twig

    {{ grid('product') }}
    

    The bundle provides built-in Twig extensions for rendering grids.


First Use Case: Displaying a List of Products

  1. Define Fields in product.yaml

    sylius_grid:
        grids:
            product:
                driver:
                    name: doctrine/orm
                    options:
                        class: App\Entity\Product
                fields:
                    id:
                        type: twig
                        options:
                            template: '@SyliusGrid/Field/id.html.twig'
                    name:
                        type: twig
                        options:
                            template: '@SyliusGrid/Field/text.html.twig'
                actions:
                    item:
                        edit:
                            type: edit
                            options:
                                route: sylius_admin_product_edit
    
  2. Load and Display

    $grid = $gridFactory->create('product');
    $grid->load(); // Executes queries, applies filters/sorting
    return $this->render('product/index.html.twig', ['grid' => $grid]);
    
  3. Customize with Filters/Sorting

    filters:
        search:
            type: string
            options:
                label: 'Search'
                field: name
    sorting:
        name:
            label: Name
            default: true
    

Implementation Patterns

Core Workflows

1. Grid Definition

  • YAML/Php Configuration: Define grids in config/grids/*.{yaml,php}.
    // config/grids/product.php
    return [
        'driver' => [
            'name' => 'doctrine/orm',
            'options' => ['class' => App\Entity\Product::class],
        ],
        'fields' => [
            'name' => ['type' => 'twig', 'options' => ['template' => '@App/Grid/Field/name.html.twig']],
        ],
    ];
    
  • Dynamic Grids: Use GridFactory to create grids programmatically:
    $grid = $gridFactory->create('product', [
        'fields' => ['price' => ['type' => 'price']],
    ]);
    

2. Field Types

  • Built-in Types: text, date, price, boolean, enum, etc.
    fields:
        status:
            type: enum
            options:
                choices: ['draft', 'published', 'archived']
    
  • Custom Fields: Implement FieldTypeInterface:
    class CustomFieldType implements FieldTypeInterface
    {
        public function render(FieldView $view, array $options): string
        {
            return sprintf('<span>%s</span>', $view->getData());
        }
    }
    
    Register as a service with the sylius.grid.field_type tag.

3. Filters and Sorting

  • Filter Types: string, number, date, enum, entity, etc.
    filters:
        category:
            type: entity
            options:
                field: category
                choices: '@sylius.repository.category'
    
  • Sorting: Define in YAML or dynamically:
    $grid->getSorting()->add('createdAt', 'desc');
    

4. Actions

  • Built-in Actions: edit, delete, view.
    actions:
        item:
            edit:
                type: edit
                options:
                    route: app_admin_product_edit
                    routeParameters:
                        id: resource.id
    
  • Custom Actions: Implement ActionTypeInterface:
    class CustomActionType implements ActionTypeInterface
    {
        public function render(ActionView $view, array $options): string
        {
            return $this->renderLink($view, $options);
        }
    }
    

5. Templating

  • Override Default Templates: Copy from vendor/sylius/grid-bundle/Resources/views/ to templates/SyliusGrid/.
  • Dynamic Templates: Use type: twig with custom templates:
    fields:
        name:
            type: twig
            options:
                template: '@App/Grid/Field/product_name.html.twig'
    

Integration Tips

1. Doctrine Integration

  • Use doctrine/orm driver for Eloquent-like queries:
    driver:
        name: doctrine/orm
        options:
            class: App\Entity\Product
            repository: '@sylius.repository.product'
    
  • Custom Repositories: Pass a custom repository service:
    driver:
        name: doctrine/orm
        options:
            repository: '@app.custom_product_repository'
    

2. API Grids

  • Use json driver for API responses:
    driver:
        name: json
        options:
            data: '@sylius.grid.data_collector.product'
    
  • Serialization: Customize with SerializerInterface:
    $grid->getDataCollector()->setSerializer(new JsonSerializer());
    

3. Event Listeners

  • Modify grid behavior via events:
    // src/EventListener/GridSubscriber.php
    class GridSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                GridEvents::PRE_LOAD => 'onPreLoad',
            ];
        }
    
        public function onPreLoad(GridEvent $event): void
        {
            $grid = $event->getGrid();
            $grid->getFilters()->add('custom', new CustomFilter());
        }
    }
    

4. Testing

  • Functional Tests: Use GridTestTrait:
    use Sylius\Bundle\GridBundle\Tests\Functional\GridTestTrait;
    
    class ProductGridTest extends WebTestCase
    {
        use GridTestTrait;
    
        public function testGridRendering(): void
        {
            $grid = $this->getGrid('product');
            $this->assertCount(10, $grid->getResults());
        }
    }
    
  • Unit Tests: Mock GridFactory and test field types/actions.

Gotchas and Tips

Pitfalls

  1. Driver Mismatch

    • Issue: Using doctrine/orm without proper repository or class configuration.
    • Fix: Ensure the driver options match your entity/repository:
      driver:
          name: doctrine/orm
          options:
              class: App\Entity\Product
              repository: '@sylius.repository.product' # Required if not autowirable
      
  2. Field Type Conflicts

    • Issue: Overriding built-in field types without proper namespace.
    • Fix: Use unique service IDs for custom field types:
      services:
          app.grid.field_type.custom:
              class: App\Grid\Field\CustomFieldType
              tags: [sylius.grid.field_type]
      
  3. Circular Dependencies in Grids

    • Issue: Grids referencing each other (e.g., Product grid filtering by Category grid).
    • Fix: Use lazy loading or ensure grids are defined in a dependency-ordered sequence.
  4. Enum Support Quirks

    • Issue: EnumField not displaying choices correctly.
    • Fix: Ensure the enum class is properly mapped and choices are defined:
      fields:
          status:
              type: enum
              options:
                  choices: ['draft', 'published', 'archived']
                  enum_class: App\Enum\ProductStatus
      
  5. Action Route Parameters

    • Issue: routeParameters not passing dynamic values.
    • Fix: Use resource.* placeholders:
      actions:
          item:
              edit:
                  type: edit
                  options:
                      route: app_admin_product_edit
                      routeParameters:
                          id: resource.id
      

Debugging Tips

  1. Enable Grid Debugging
    • Dump
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
phalcon/cli-options-parser
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi