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

thrace/datagrid-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    "require": {
        "thrace/datagrid-bundle": "^1.0"
    }
    

    Run composer update.

  2. Enable the Bundle Add to config/bundles.php:

    Thrace\DataGridBundle\ThraceDataGridBundle::class => ['all' => true],
    
  3. Basic Twig Usage Create a grid definition in a Twig template:

    {{ thrace_datagrid({
        'source': 'App\Entity\User',
        'columns': [
            { 'name': 'id', 'index': 'id', 'width': 50, 'sortable': true },
            { 'name': 'username', 'index': 'username', 'width': 200 }
        ]
    }) }}
    
  4. First Use Case: Simple CRUD Grid Define a grid in a controller to fetch and display users:

    // src/Controller/UserController.php
    use Thrace\DataGridBundle\ThraceDataGridBundle;
    
    public function indexAction()
    {
        return $this->render('user/index.html.twig', [
            'grid' => $this->get('thrace.datagrid')->createGrid('user_grid')
        ]);
    }
    

Implementation Patterns

Core Workflows

  1. Grid Definition Use YAML/XML or PHP arrays to define grids in config/grid.yml:

    user_grid:
        source: App\Entity\User
        columns:
            - { name: 'id', index: 'id', width: 50 }
            - { name: 'email', index: 'email', width: 200 }
        pager: true
        rowNum: 10
    
  2. Dynamic Column Configuration Override columns in Twig:

    {{ thrace_datagrid(grid, {
        'columns': [
            { 'name': 'actions', 'index': 'actions', 'formatter': 'actions', 'width': 100 }
        ]
    }) }}
    
  3. Query Building with Search/Filter Use the search and filter options to build complex queries:

    {{ thrace_datagrid(grid, {
        'search': true,
        'filter': {
            'groupOp': 'AND',
            'rules': [
                { 'field': 'username', 'op': 'cn', 'data': 'john' }
            ]
        }
    }) }}
    
  4. Inline Editing Enable inline editing for a column:

    columns:
        - { name: 'email', index: 'email', editable: true, editrules: { required: true } }
    
  5. Mass Actions Define mass actions in YAML:

    mass_actions:
        delete:
            label: 'Delete'
            action: 'user_delete'
            confirm: 'Are you sure?'
    
  6. Dependent Grids Link grids via foreign keys:

    dependent_grids:
        orders:
            source: App\Entity\Order
            foreign_key: user_id
    

Integration Tips

  • Doctrine Integration Use DQL or QueryBuilder for custom queries:

    source:
        type: dql
        query: SELECT u FROM App\Entity\User u WHERE u.active = 1
    
  • Custom Formatter Extend the bundle to add custom formatters:

    // src/Thrace/DataGridBundle/Formatter/StatusFormatter.php
    class StatusFormatter extends AbstractFormatter
    {
        public function format($cell, $rowData, $colModel, $rowId)
        {
            return $cell ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
        }
    }
    
  • Event Listeners Subscribe to grid events for pre/post-processing:

    // src/EventSubscriber/DataGridSubscriber.php
    class DataGridSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                ThraceDataGridEvents::PRE_BUILD_QUERY => 'onPreBuildQuery',
            ];
        }
    
        public function onPreBuildQuery(PreBuildQueryEvent $event)
        {
            $event->getQueryBuilder()->andWhere('u.deleted_at IS NULL');
        }
    }
    
  • AJAX Handling Use Symfony’s JsonResponse for custom AJAX endpoints:

    public function getGridDataAction(Request $request)
    {
        $grid = $this->get('thrace.datagrid')->createGrid('user_grid');
        $data = $grid->getData($request->query->all());
        return new JsonResponse($data);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Twig Environment Requirement

    • Issue: The bundle only works in Twig. Using it with PHP templates (e.g., render() without Twig) will fail.
    • Fix: Ensure your templates extend a Twig base template or use render() with Twig explicitly:
      return $this->render('template.html.twig');
      
  2. Doctrine Proxy Issues

    • Issue: Lazy-loaded Doctrine proxies may cause serialization errors when fetching grid data.
    • Fix: Use DISTINCT in queries or initialize proxies:
      source:
          type: dql
          query: SELECT DISTINCT u FROM App\Entity\User u
      
  3. jqGrid Version Mismatch

    • Issue: The bundle assumes a specific version of jqGrid. Updating jqGrid may break functionality.
    • Fix: Check the bundle’s Resources/public/js/ for version dependencies and update accordingly.
  4. Pagination Conflicts

    • Issue: Custom pagination logic may override the bundle’s built-in pager.
    • Fix: Disable the pager in the grid config if using custom pagination:
      pager: false
      
  5. Mass Action Security

    • Issue: Mass actions (e.g., delete) can be exploited if not properly secured.
    • Fix: Always validate user permissions in the action handler:
      public function userDeleteAction(Request $request)
      {
          $this->denyAccessUnlessGranted('ROLE_ADMIN');
          // Proceed with deletion
      }
      
  6. Column Index vs. Property Name

    • Issue: Confusing index (used for sorting/filtering) with name (display name) can lead to broken queries.
    • Fix: Ensure index matches the database column or DQL alias:
      columns:
          - { name: 'Full Name', index: 'u.firstname', width: 150 }
      

Debugging Tips

  1. Enable Query Logging Add to config/packages/dev/doctrine.yaml:

    doctrine:
        dbal:
            logging: true
            profiling: true
    

    Check logs for generated SQL queries.

  2. Inspect Grid Data Dump grid data in a controller to verify structure:

    $grid = $this->get('thrace.datagrid')->createGrid('user_grid');
    $data = $grid->getData($request->query->all());
    dump($data); // Check for expected structure
    
  3. Check Browser Console jqGrid errors often appear in the browser’s console. Look for:

    • 404 errors (missing JS/CSS).
    • JSON parsing errors (invalid data format).
  4. Validate YAML Configuration Use Symfony’s validator to check for syntax errors:

    php bin/console debug:config thrace_datagrid
    

Extension Points

  1. Custom Query Builders Extend Thrace\DataGridBundle\Query\QueryBuilder to support non-Doctrine sources (e.g., Elasticsearch):

    class ElasticQueryBuilder extends AbstractQueryBuilder
    {
        public function buildQuery(array $options)
        {
            // Custom Elasticsearch logic
        }
    }
    
  2. Add Custom Grid Types Implement Thrace\DataGridBundle\Grid\GridInterface for specialized grids (e.g., read-only grids):

    class ReadOnlyGrid implements GridInterface
    {
        public function render(array $options)
        {
            // Custom rendering logic
        }
    }
    
  3. Override Twig Functions Extend the bundle’s Twig environment to add custom functions:

    // src/Thrace/DataGridBundle/DependencyInjection/Compiler/TwigPass.php
    public function process(ContainerBuilder $container)
    {
        $twig = $container->getDefinition('twig');
        $twig->addMethodCall('addFunction', [
            new Expression('new \Thrace\DataGridBundle\Twig\CustomGridFunction()'),
        ]);
    }
    
  4. Hook into Grid Events Use events for pre/post

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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle