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

Datagrid Bundle Laravel Package

domenik88/datagrid-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require domenik88/datagrid-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Domenik88\DataGridBundle\Domenik88DataGridBundle::class => ['all' => true],
    ];
    
  2. First Grid Definition Create a YAML config file (e.g., config/datagrids/users.yml):

    users:
        datasource:
            type: orm
            entity: App\Entity\User
        columns:
            - { name: id, label: 'ID' }
            - { name: username, label: 'Username' }
            - { name: email, label: 'Email' }
    
  3. Render in Controller

    use Domenik88\DataGridBundle\Grid\GridFactory;
    
    public function indexAction(GridFactory $gridFactory)
    {
        $grid = $gridFactory->create('users');
        return $this->render('users/index.html.twig', ['grid' => $grid]);
    }
    
  4. Twig Template

    {{ grid.render() }}
    

First Use Case: Basic CRUD Grid

  • Sorting: Click column headers (e.g., username).
  • Filtering: Use the default text input for username or email.
  • Pagination: Built-in via limit and offset in the datasource.

Implementation Patterns

1. Datasource Configuration

  • ORM (Doctrine): Default for entities.
    datasource:
        type: orm
        entity: App\Entity\User
        repository_method: findAll  # Optional custom repo method
    
  • ODM (MongoDB): For documents.
    datasource:
        type: odm
        document: App\Document\Product
    
  • Array (Vector): For raw data.
    datasource:
        type: vector
        data: %app.some_array_data%
    

2. Column Auto-Typing

Leverage automatic type detection for rich UI/UX:

columns:
    - { name: price, label: 'Price', type: currency, locale: 'en_US' }
    - { name: is_active, label: 'Active', type: boolean }
    - { name: created_at, label: 'Created At', type: datetime }

3. Filtering Patterns

  • Dynamic Select Filters:
    filters:
        category:
            type: select
            data_source: method
            data_source_method: getCategories
            data_source_entity: App\Entity\Category
    
  • Range Filters (for numbers/dates):
    filters:
        price:
            type: range
            from: 0
            to: 1000
    

4. Mass Actions

Define bulk operations in YAML:

mass_actions:
    delete:
        type: delete
        label: 'Delete Selected'
        icon: trash
        route: user_delete_mass
        route_parameters:
            ids: $ids

5. Row Actions

Add per-row buttons:

row_actions:
    edit:
        type: link
        label: 'Edit'
        route: user_edit
        route_parameters:
            id: $id
    view:
        type: link
        label: 'View'
        route: user_view
        route_parameters:
            id: $id

6. Export Integration

Trigger exports via Twig:

<a href="{{ path('user_export', { grid: 'users', format: 'csv' }) }}">Export CSV</a>

Configure exports in YAML:

exports:
    csv:
        enabled: true
        label: 'CSV'
    excel:
        enabled: true
        label: 'Excel'

7. Dynamic Grids

Use Twig to pass dynamic configs:

{% set gridConfig = {
    'datasource': {
        'type': 'orm',
        'entity': 'App\Entity\\' ~ userType
    },
    'columns': columns
} %}
{{ grid.render(gridConfig) }}

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in YAML

    • Column names in YAML must match entity property names exactly (including case).
    • Fix: Use mapping to alias:
      columns:
          - { name: user_id, label: 'User ID', mapping: id }
      
  2. Locale Mismatches

    • If locale is not set for datetime/currency, defaults to system locale.
    • Fix: Explicitly define:
      columns:
          - { name: price, type: currency, locale: 'en_US' }
      
  3. Mass Action Route Conflicts

    • Ensure route_parameters in mass actions match your route definitions.
    • Fix: Use route_name instead of route for clarity:
      mass_actions:
          archive:
              type: link
              label: 'Archive'
              route_name: user_archive
              route_parameters: { ids: $ids }
      
  4. Performance with Large Datasets

    • Avoid findAll() for tables >10K rows. Use createQueryBuilder() in custom repo methods.
    • Tip: Add query_builder to datasource:
      datasource:
          type: orm
          entity: App\Entity\Order
          query_builder: App\Repository\OrderRepository::createAdminQueryBuilder
      
  5. Twig Template Caching

    • Clear cache after modifying grid configs:
      php bin/console cache:clear
      

Debugging Tips

  1. Dump Grid Config Add to controller to inspect:

    dump($grid->getConfig());
    
  2. Check Query Logs Enable Doctrine logging to verify queries:

    // config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  3. Filter Debugging Use filter_data in Twig to inspect submitted filters:

    <pre>{{ dump(grid.getFilterData()) }}</pre>
    

Extension Points

  1. Custom Filter Types Extend Domenik88\DataGridBundle\Filter\FilterInterface:

    class CustomFilter implements FilterInterface { ... }
    

    Register in services:

    services:
        app.custom_filter:
            class: App\Filter\CustomFilter
            tags:
                - { name: datagrid.filter_type, type: custom }
    
  2. Override Twig Rendering Extend the base template (@Domenik88DataGrid/grid.html.twig) in your theme.

  3. Dynamic Column Types Use type: callback for custom logic:

    columns:
        - { name: status, type: callback, callback: App\DataGrid\StatusType }
    

    Implement Domenik88\DataGridBundle\Type\ColumnTypeInterface.

  4. Event Listeners Hook into grid lifecycle:

    use Domenik88\DataGridBundle\Event\GridEvents;
    
    $dispatcher->addListener(GridEvents::PRE_BUILD, function ($event) {
        $event->getGrid()->addColumn(...);
    });
    

Pro Tips

  1. Reuse Grids Across Controllers Define grids in YAML and inject via GridFactory:

    $grid = $gridFactory->create('users', $customConfig);
    
  2. Conditional Columns Use visible to toggle columns:

    columns:
        - { name: admin_only, visible: false }  # Hidden by default
    

    Toggle via JS or Twig:

    {{ grid.showColumn('admin_only') }}
    
  3. Inline Editing Combine with row_actions and AJAX for quick edits:

    row_actions:
        edit_inline:
            type: ajax
            label: 'Edit'
            route: user_edit_inline
            route_parameters: { id: $id }
    
  4. Multi-Grid Forms Chain grids for hierarchical data:

    {{ grid.render('orders') }}
    {% for order in grid.getResults() %}
        {{ grid.render('order_items', { order_id: order.id }) }}
    {% endfor %}
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui