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

Data Grid Laravel Package

ano/data-grid

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ano/data-grid
    

    Ensure your project uses PHP 5.3+ and Twig 1.x (as per composer.json).

  2. Basic Usage

    • Load the grid class:
      require_once 'vendor/autoload.php';
      use Ano\DataGrid\DataGrid;
      
    • Initialize a grid with data:
      $grid = new DataGrid();
      $grid->setDataSource($yourDataArray); // Array of associative arrays
      
  3. First Use Case: Rendering a Simple Table

    $grid->setColumns([
        'id' => ['title' => 'ID', 'width' => 50],
        'name' => ['title' => 'Name', 'width' => 200],
    ]);
    echo $grid->render();
    
    • Outputs a Twig-rendered HTML table with pagination/sorting if configured.

Implementation Patterns

Core Workflows

  1. Data Binding

    • Use setDataSource() with an array of associative arrays (e.g., from a database query).
    • Example:
      $users = User::all()->toArray();
      $grid->setDataSource($users);
      
  2. Column Configuration

    • Define columns with titles, widths, and callbacks:
      $grid->setColumns([
          'id' => ['title' => 'ID', 'width' => 50],
          'email' => [
              'title' => 'Email',
              'width' => 250,
              'callback' => function($value) {
                  return '<a href="mailto:'.$value.'">'.$value.'</a>';
              }
          ],
      ]);
      
  3. Pagination & Sorting

    • Enable via setPagination() and setSortableColumns():
      $grid->setPagination(10); // Items per page
      $grid->setSortableColumns(['id', 'name']);
      
  4. Twig Integration

    • Override the default Twig template by passing a custom path:
      $grid->setTemplatePath(__DIR__.'/custom_grid.html.twig');
      
    • Extend the template to add custom logic (e.g., row classes, conditional styling).
  5. Server-Side Processing

    • For large datasets, use setServerSide(true) to fetch data via AJAX (requires frontend JS integration).

Integration Tips

  • Laravel-Specific:

    • Bind grid data to a controller method and pass to a view:
      public function showGrid() {
          $grid = new DataGrid();
          $grid->setDataSource(User::paginate(10)->toArray());
          return view('grid', ['grid' => $grid]);
      }
      
    • Use Laravel’s Blade alongside Twig by rendering the grid output in a Blade template:
      {!! $grid->render() !!}
      
  • Dynamic Columns:

    • Fetch column definitions from a database or config:
      $columns = config('grid.columns');
      $grid->setColumns($columns);
      
  • Localization:

    • Override Twig translations (e.g., "Previous", "Next") by extending the template or using Twig’s trans filter.

Gotchas and Tips

Pitfalls

  1. PHP 5.3 Legacy:

    • Avoid modern PHP features (e.g., arrow functions, type hints). Use anonymous functions with function($x) {} syntax.
    • Example of incompatible code:
      // ❌ Fails in PHP 5.3
      $grid->setCallback(fn($x) => $x * 2);
      
      // ✅ Works
      $grid->setCallback(function($x) { return $x * 2; });
      
  2. Twig Dependency:

    • The package requires Twig 1.x. Conflicts may arise with Laravel’s default Twig 2.x. Downgrade Twig or use a separate Twig environment:
      composer require twig/twig:^1.27
      
  3. Pagination Quirks:

    • setPagination() expects total items, not pages. For Laravel paginators, use:
      $grid->setPagination(User::count());
      $grid->setDataSource(User::paginate(10)->items());
      
  4. Callback Scope:

    • Callbacks receive raw data. Sanitize outputs to prevent XSS:
      'callback' => function($value) {
          return htmlspecialchars($value, ENT_QUOTES);
      }
      
  5. No Laravel Service Provider:

    • The package lacks Laravel integration (e.g., no DataGridServiceProvider). Register it manually in AppServiceProvider if needed:
      $this->app->singleton(DataGrid::class, function() {
          return new DataGrid();
      });
      

Debugging Tips

  1. Inspect Rendered HTML:

    • Use var_dump($grid->render()) to debug Twig output before rendering to the browser.
  2. Check Data Source:

    • Verify setDataSource() receives an array of arrays (not objects or collections). Convert with:
      $grid->setDataSource(User::get()->toArray());
      
  3. Twig Errors:

    • Enable Twig’s debug mode:
      $twig = new \Twig_Environment($loader, [
          'debug' => true,
      ]);
      
  4. Sorting Issues:

    • Ensure setSortableColumns() includes valid array keys from your data source.

Extension Points

  1. Custom Templates:

    • Extend the default Twig template (vendor/ano/data-grid/templates/default.html.twig) by copying it to your project and overriding paths.
  2. Add-ons:

    • Implement row callbacks for dynamic classes:
      $grid->setRowCallback(function($row, $index) {
          return ['class' => $index % 2 ? 'odd' : 'even'];
      });
      
    • Add toolbar buttons by extending the template’s {{ grid.toolbar }} block.
  3. Server-Side AJAX:

    • Use setServerSide(true) and handle requests in a controller:
      public function gridData(Request $request) {
          $grid = new DataGrid();
          $grid->setServerSide(true);
          $grid->setDataSource(User::query()->get());
          return response()->json($grid->getServerSideData());
      }
      
    • Pair with frontend JS (e.g., jQuery) to fetch data dynamically.
  4. Export Features:

    • Extend the template to add CSV/Excel export buttons by leveraging libraries like maatwebsite/excel.
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields