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

Ux Gridjs Laravel Package

alexain/ux-gridjs

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require alexain/ux-gridjs
    

    Ensure your project meets the requirements:

    • PHP ≥ 8.2
    • Symfony 7.x/8.x
    • symfony/asset-mapper and symfony/stimulus-bundle installed.
  2. Register Grid.js via AssetMapper

    php bin/console importmap:require gridjs
    php bin/console importmap:install
    

    This auto-generates the importmap for Grid.js.

  3. Enable the Stimulus Controller The bundle ships with grid_controller.js. Ensure it’s registered in your Stimulus app (check config/packages/stimulus.yaml or your Stimulus entrypoint).


First Use Case: Basic Table Rendering

  1. Create a Grid Presenter In your controller or service, use GridPresenter to define columns and data:

    use Alexain\UXGridJs\GridPresenter;
    
    $grid = (new GridPresenter())
        ->setColumns([
            ['name' => 'id', 'title' => 'ID'],
            ['name' => 'name', 'title' => 'Name'],
        ])
        ->setData($yourDataArray);
    
  2. Render in Twig Pass the grid to your template:

    {{ gridjs_render(grid) }}
    

    This outputs a <div data-controller="grid"> with the grid configuration.

  3. View the Table The Stimulus controller initializes Grid.js, rendering the table client-side.


Optional: Turbo Drive Integration

If using Turbo Drive, ensure your layout includes:

{% block stylesheets %}
    {{ parent() }}
    {{ importmap('app') }} {# Auto-includes Grid.js #}
{% endblock %}

Implementation Patterns

Workflow: Backend-Driven Configuration

  1. Define Grid Logic in Controllers/Services Use GridPresenter to encapsulate table logic (columns, sorting, filtering):

    $grid = (new GridPresenter())
        ->setColumns([
            ['name' => 'created_at', 'title' => 'Date', 'type' => 'date'],
            ['name' => 'status', 'title' => 'Status', 'filter' => true],
        ])
        ->setData($repository->findAll())
        ->setSearch(true)
        ->setSort(true);
    
  2. Reuse Presenters Create a service to centralize grid configurations:

    // src/Service/UserGridService.php
    class UserGridService {
        public function getGrid(): GridPresenter {
            return (new GridPresenter())
                ->setColumns([...])
                ->setData($this->userRepository->findAll());
        }
    }
    
  3. Pass to Twig Inject the service into your controller and render:

    public function index(UserGridService $gridService): Response {
        return $this->render('user/index.html.twig', [
            'grid' => $gridService->getGrid(),
        ]);
    }
    

Integration Tips

  1. Dynamic Data Loading Use Stimulus actions to fetch data via API:

    // grid_controller.js (extend the default)
    connect() {
        this.grid = gridjs.Grid(this.element, this.gridConfig);
        // Add custom fetch logic
        this.element.addEventListener('grid:refresh', () => {
            fetch('/api/users').then(response => {
                this.grid.updateData(response.data);
            });
        });
    }
    
  2. Toolbar Buttons Configure buttons server-side (no Twig overrides):

    $grid->setToolbar([
        'buttons' => [
            ['text' => 'Add', 'action' => 'addUser'],
            ['text' => 'Export', 'action' => 'exportCsv'],
        ],
    ]);
    

    Handle actions via Stimulus:

    // grid_controller.js
    addUser() {
        Turbo.visit('/users/new');
    }
    
  3. Pagination Use setPagination(true) and configure server-side:

    $grid->setPagination([
        'server' => true,
        'pageSize' => 10,
    ]);
    

    Handle pagination via API endpoints (e.g., /api/users?page=2).


Asset Management

  • Custom CSS/JS: Override Grid.js styles by adding your own importmap entry:

    php bin/console importmap:require custom-grid-styles
    

    Then include it in your Twig template:

    {{ importmap('custom-grid-styles') }}
    
  • Lazy Loading: Defer Grid.js initialization until the table is visible:

    // grid_controller.js
    connect() {
        if (this.hasElementVisible()) {
            this.grid = gridjs.Grid(this.element, this.gridConfig);
        } else {
            this.element.addEventListener('show', () => this.initGrid());
        }
    }
    

Gotchas and Tips

Pitfalls

  1. AssetMapper Cache After running importmap:install, clear your cache:

    php bin/console cache:clear
    

    If Grid.js fails to load, verify the importmap entry exists in public/build/importmap.json.

  2. Stimulus Controller Naming Ensure grid_controller.js is registered in config/packages/stimulus.yaml:

    stimulus:
        controllers:
            grid: 'Alexain\UXGridJs\Asset\grid_controller.js'
    
  3. Twig Template Overrides Avoid overriding gridjs_render in Twig. Instead, extend the Stimulus controller for custom behavior.

  4. Turbo Drive Conflicts If using Turbo, ensure your grid container has data-turbo-permanent to prevent reinitialization:

    <div data-controller="grid" data-turbo-permanent>
        {{ gridjs_render(grid) }}
    </div>
    

Debugging

  1. Check Console Errors Open browser dev tools (F12) to verify Grid.js and Stimulus are loaded:

    Uncaught ReferenceError: gridjs is not defined
    

    → Run importmap:install again.

  2. Inspect Stimulus Controller Add debug logs to grid_controller.js:

    connect() {
        console.log('Grid config:', this.gridConfig); // Debug output
        this.grid = gridjs.Grid(this.element, this.gridConfig);
    }
    
  3. Data Binding Issues If data doesn’t render, ensure setData() returns an array of arrays:

    // Correct:
    $grid->setData([['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']]);
    
    // Incorrect (will fail silently):
    $grid->setData($yourEntityObjects); // Use ->toArray() first!
    

Extension Points

  1. Custom Column Types Extend Grid.js column types in your Stimulus controller:

    // grid_controller.js
    connect() {
        this.grid = gridjs.Grid(this.element, {
            columns: [
                { name: 'status', title: 'Status', formatter: (cell) => {
                    return cell === 'active' ? '<span class="text-green">Active</span>' : 'Inactive';
                }},
            ],
        });
    }
    
  2. Server-Side Sorting/Filters Proxy client-side events to your API:

    // grid_controller.js
    connect() {
        this.grid = gridjs.Grid(this.element, this.gridConfig);
        this.grid.on('sort', (event) => {
            Turbo.visit(`/users?sort=${event.column}&dir=${event.direction}`);
        });
    }
    
  3. Plugin Integration Use Grid.js plugins (e.g., gridjs-plugin-filter) by extending the controller:

    import { GridJsPluginFilter } from 'gridjs-plugin-filter';
    
    connect() {
        this.grid = gridjs.Grid(this.element, this.gridConfig);
        GridJsPluginFilter(this.grid);
    }
    

    Ensure the plugin is imported via AssetMapper.


Configuration Quirks

  1. Default Pagination If setPagination(true) is called without options, it defaults to:

    {
        server: false,
        pageSize: 10,
        navigate: true,
    }
    
  2. Toolbar Button Actions Button actions are passed as strings (e.g., 'action' => 'export'). Handle them in Stimulus:

    // grid_controller.js
    exportCsv() {
        window.open('/api/users/export');
    }
    
  3. Turbo Drive + GridJs Turbo Drive may re-render the page, causing Grid.js to reinitialize. Mitigate with:

    // grid_controller.js
    connect() {
        if (this.grid) return; // Skip if already initialized
        this.grid = gridjs.Grid(this.element, this.gridConfig);
    }
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium