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 Setup

  1. Installation:

    composer require sylius/grid-bundle
    

    Ensure SyliusGridBundle is enabled in config/bundles.php:

    return [
        // ...
        Sylius\GridBundle\SyliusGridBundle::class => ['all' => true],
    ];
    
  2. First Grid Definition: Create a grid configuration YAML file (e.g., config/grids/product_grid.yaml):

    sylius_grid:
        grids:
            product:
                driver:
                    name: doctrine/orm
                    options:
                        class: App\Entity\Product
                sorting:
                    name: ^name
                fields:
                    name:
                        type: string
                        label: Name
                    price:
                        type: twig
                        label: Price
                        options:
                            template: "@SyliusGrid/Field/price.html.twig"
    
  3. First Usage in Controller:

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

    {{ grid('product') }}
    

First Use Case: Admin Product List

  • Use the grid to display a paginated, sortable, and filterable list of products in an admin panel.
  • Leverage built-in filters (e.g., string, entity, date) and custom fields (e.g., price, stock).

Implementation Patterns

Common Workflows

1. Dynamic Grid Configuration

  • Use Case: Load grid configurations dynamically (e.g., based on user roles or permissions).
  • Pattern:
    # config/grids/admin_product_grid.yaml
    sylius_grid:
        grids:
            admin_product:
                driver: doctrine/orm
                options:
                    class: App\Entity\Product
                    repository_method: findAdminProducts
                # ...
    
    // In a service or controller
    $gridName = $user->hasRole('ROLE_ADMIN') ? 'admin_product' : 'public_product';
    $grid = $gridFactory->create($gridName, $request);
    

2. Custom Field Types

  • Use Case: Display complex data (e.g., product images, nested entities).
  • Pattern:
    fields:
        thumbnail:
            type: twig
            label: Thumbnail
            options:
                template: "@App/Grid/Field/product_thumbnail.html.twig"
    
    {# templates/grid/field/product_thumbnail.html.twig #}
    <img src="{{ field.value.imageUrl }}" alt="{{ field.value.name }}">
    

3. Filter Integration

  • Use Case: Add filters for specific use cases (e.g., stock status, categories).
  • Pattern:
    filters:
        stock_status:
            type: entity
            label: Stock Status
            options:
                field: stockStatus
                choices: ['in_stock', 'out_of_stock']
    

4. Action Buttons

  • Use Case: Add action buttons (e.g., "Edit", "Delete") to grid rows.
  • Pattern:
    actions:
        edit:
            type: edit
            label: Edit
            options:
                route: sylius_admin_product_update
                parameters:
                    id: id
        delete:
            type: delete
            label: Delete
            options:
                route: sylius_admin_product_delete
                parameters:
                    id: id
    
    {{ grid('product')|sylius_grid_action_row }}
    

5. Data Providers

  • Use Case: Fetch data from external APIs or custom repositories.
  • Pattern:
    driver:
        name: custom
        options:
            service: app.product_data_provider
    
    // src/Service/ProductDataProvider.php
    class ProductDataProvider implements DataProviderInterface
    {
        public function load(array $criteria): array
        {
            // Custom logic (e.g., API call)
            return $products;
        }
    }
    

6. Twig Extensions

  • Use Case: Extend grid rendering with custom logic.
  • Pattern:
    // src/Twig/GridExtension.php
    class GridExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions(): array
        {
            return [
                new \Twig\TwigFunction('custom_grid_field', [$this, 'renderCustomField']),
            ];
        }
    
        public function renderCustomField(array $field): string
        {
            // Custom rendering logic
            return $field['value'];
        }
    }
    
    {{ custom_grid_field(field) }}
    

Integration Tips

Symfony Forms Integration

  • Use grid data to pre-fill Symfony forms:
    $product = $grid->getResult()->first();
    $form = $this->createForm(ProductType::class, $product);
    

API Responses

  • Serialize grid data for API responses:
    use Sylius\Bundle\GridBundle\Grid\GridInterface;
    
    $data = $grid->getResult()->toArray();
    return $this->json($data);
    

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
        {
            $event->getGrid()->addFilter('custom_filter');
        }
    }
    

Gotchas and Tips

Pitfalls

1. Caching Issues

  • Problem: Grid data may not update immediately due to caching (e.g., Doctrine result cache).
  • Fix: Clear cache after data changes:
    php bin/console cache:clear
    
    Or disable caching for specific grids:
    driver:
        options:
            cache: false
    

2. Field Type Mismatches

  • Problem: Using incorrect field types (e.g., string for a DateTime field) causes errors.
  • Fix: Validate field types in YAML and ensure entity properties match:
    fields:
        created_at:
            type: datetime  # Correct type for DateTime properties
            label: Created At
    

3. Permission-Based Grids

  • Problem: Hardcoding grid names in controllers bypasses role-based access.
  • Fix: Use a service to resolve grid names dynamically:
    class GridResolver
    {
        public function resolve(string $requestedGridName, UserInterface $user): string
        {
            return $user->hasRole('ROLE_ADMIN') ? 'admin_grid' : 'public_grid';
        }
    }
    

4. Performance with Large Datasets

  • Problem: Slow loading with thousands of records.
  • Fix:
    • Use pagination:
      pagination:
          items_per_page: 50
      
    • Optimize queries with DQL:
      driver:
          options:
              dql: SELECT p FROM App\Entity\Product p WHERE p.enabled = true
      

5. Twig Template Overrides

  • Problem: Overriding templates may not work due to incorrect namespace or caching.
  • Fix:
    • Place custom templates in templates/bundles/SyliusGridBundle/ or templates/SyliusGridBundle/.
    • Clear Twig cache:
      php bin/console cache:clear
      

Debugging Tips

1. Enable Grid Debugging

  • Enable debug mode in config/packages/sylius_grid.yaml:
    sylius_grid:
        debug: true
    
  • Check logs for grid-related errors:
    php bin/console debug:container sylius.grid
    

2. Inspect Grid Criteria

  • Dump grid criteria to debug filtering/sorting:
    $grid = $gridFactory->create('product', $request);
    dump($grid->getCriteria());
    

3. Check Driver Configuration

  • Validate driver options (e.g., Doctrine entity manager, custom service):
    driver:
        name: doctrine/orm
        options:
            entity_manager: default  # Ensure correct EM name
    

4. Field-Specific Debugging

  • Use Twig dump to inspect field data:
    {{ dump(field) }}
    

Extension Points

1. Custom Drivers

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware