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

apy/datagrid-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require apy/datagrid-bundle

Add the bundle to config/bundles.php:

return [
    // ...
    APY\DataGridBundle\APYDataGridBundle::class => ['all' => true],
];
  1. First Grid (ORM Example): Create a controller method to initialize a grid:

    use APY\DataGridBundle\Grid\Source\Entity;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class ProductController extends AbstractController
    {
        public function listAction()
        {
            $source = new Entity('App\Entity\Product');
            $grid = $this->get('grid');
            $grid->setSource($source);
            return $this->render('product/list.html.twig', [
                'grid' => $grid->getGridResponse('product/_grid.html.twig')
            ]);
        }
    }
    
  2. Basic Twig Template: Create templates/product/_grid.html.twig:

    {{ grid(grid) }}
    
  3. Clear Cache:

    php bin/console cache:clear
    

First Use Case: Displaying a Simple Entity List

  • Entity Annotations:
    use APY\DataGridBundle\Grid\Mapping as GRID;
    
    /**
     * @GRID\Source(columns="id, name, price")
     */
    class Product {}
    
  • Controller:
    $grid->setSource(new Entity('App\Entity\Product'));
    $grid->setTitle('Products');
    return $this->render('product/list.html.twig', ['grid' => $grid]);
    

Implementation Patterns

Common Workflows

1. Dynamic Column Configuration

Use PHP or YAML to define columns dynamically:

# config/packages/apy_datagrid.yaml
services:
    App\Grid\ProductGrid:
        tags: [apy.datagrid]
        arguments:
            $columns:
                - { name: 'name', label: 'Product Name' }
                - { name: 'price', type: 'currency', label: 'Price' }

2. Filtering with Custom Operators

Add filters to columns in the grid:

$grid->add('name', 'text', 'Name', [
    'filter' => [
        'operator' => 'contains',
        'input' => 'text'
    ]
]);

3. Exporting Data

Enable exports in the grid:

$grid->setExport([
    'csv' => true,
    'excel' => true,
    'pdf' => true
]);

4. Mass Actions

Add bulk actions:

$grid->addMassAction('delete', 'Delete', 'fa-trash', [
    'route' => 'product_delete_mass',
    'routeParams' => ['_token' => '{{ csrf_token }}']
]);

5. Ajax Loading

Configure for infinite scroll or lazy loading:

$grid->setAjax(true);
$grid->setAjaxUrl($this->generateUrl('product_ajax'));

6. Custom Templates

Override Twig templates:

{# templates/APYDataGrid/grid.html.twig #}
{% extends 'APYDataGridBundle::grid.html.twig' %}
{% block grid_row %}{{ parent() }}<custom-content>{{ row.id }}</custom-content>{% endblock %}

7. Security Roles

Restrict grid access:

$grid->setAccessControl('ROLE_ADMIN');
$grid->setColumnAccessControl([
    'price' => 'ROLE_SUPER_ADMIN'
]);

Integration Tips

Doctrine ORM/ODM

  • Use Entity or Document sources for database-backed grids.
  • Leverage Doctrine DQL for complex queries:
    $source->setDql('SELECT p FROM App\Entity\Product p WHERE p.active = :active');
    $source->setDqlParams(['active' => true]);
    

Form Integration

  • Use Symfony Forms for custom filter inputs:
    $form = $this->createFormBuilder()
        ->add('category', EntityType::class, ['class' => 'App\Entity\Category'])
        ->getForm();
    $grid->setFilterForm($form);
    

Pagination

  • Use Pagerfanta for advanced pagination:
    $source->setPagerfanta(true);
    $source->setItemsPerPage(20);
    

Localization

  • Support multiple locales:
    # config/packages/apy_datagrid.yaml
    apy_datagrid:
        locale: '%locale%'
    

Custom Columns

  • Extend column types:
    use APY\DataGridBundle\Grid\Column\ColumnInterface;
    
    class CustomColumn implements ColumnInterface
    {
        public function renderCell($value, $row)
        {
            return '<span class="custom-badge">' . $value . '</span>';
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Column Configuration:

    • Issue: Missing column definitions cause silent failures.
    • Fix: Always explicitly define columns, even if auto-detected:
      $source->setColumns(['id', 'name', 'price']);
      
  2. Ajax Filtering:

    • Issue: Filter values not URL-encoded in AJAX requests.
    • Fix: Ensure useGridPrefix is set in config/packages/apy_datagrid.yaml:
      apy_datagrid:
          use_grid_prefix: true
      
  3. Doctrine Query Issues:

    • Issue: DQL queries may fail if entity aliases are not set.
    • Fix: Use explicit aliases:
      $source->setDql('SELECT p.id AS id, p.name AS name FROM App\Entity\Product p');
      
  4. Twig Template Overrides:

    • Issue: Custom templates not loading.
    • Fix: Place overrides in templates/APYDataGrid/ and clear cache.
  5. Security Roles:

    • Issue: Roles not applied correctly.
    • Fix: Verify roles in security.yaml and use setAccessControl:
      $grid->setAccessControl(['ROLE_ADMIN', 'ROLE_EDITOR']);
      
  6. Locale Conflicts:

    • Issue: Date/number formatting inconsistent across locales.
    • Fix: Explicitly set locale in grid:
      $grid->setLocale('fr_FR');
      
  7. Mass Action Tokens:

    • Issue: CSRF tokens invalid in mass actions.
    • Fix: Use Twig syntax for tokens:
      'routeParams' => ['_token' => '{{ csrf_token("product_delete_mass") }}']
      

Debugging Tips

  1. Enable Debug Mode:

    # config/packages/dev/apy_datagrid.yaml
    apy_datagrid:
        debug: true
    
  2. Log DQL Queries:

    • Enable Doctrine logging in config/packages/dev/doctrine.yaml:
      doctrine:
          dbal:
              logging: true
              profiling: true
      
  3. Check Grid Events:

    • Listen for grid events to debug:
      $grid->on('pre_build', function($event) {
          dump($event->getGrid()->getSource()->getDql());
      });
      
  4. Validate YAML Configuration:

    • Use Symfony’s validator to check YAML configs:
      php bin/console debug:config apy_datagrid
      

Extension Points

  1. Custom Sources:

    • Extend APY\DataGridBundle\Grid\Source\SourceInterface for non-DB data:
      class ApiSource implements SourceInterface
      {
          public function load($offset, $length, array $orderBy, array $filter)
          {
              $data = $this->fetchFromApi($filter);
              return new ArrayCollection($data);
          }
      }
      
  2. Column Types:

    • Create custom column types by implementing APY\DataGridBundle\Grid\Column\ColumnInterface.
  3. Filters:

    • Extend APY\DataGridBundle\Grid\Filter\FilterInterface for custom operators.
  4. Templates:

    • Override any Twig template in templates/APYDataGrid/.
  5. Events:

    • Listen to grid events for custom logic:
      $grid->on('post_build', function($event) {
          $grid = $event->getGrid();
          // Custom logic here
      });
      
  6. Security Voters:

    • Implement APY\DataGridBundle\Grid\Security\VoterInterface for custom access control.

Configuration Quirks

  1. useGridPrefix:
    • When true, grid parameters are prefixed (e.g., `grid[filter][name
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.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
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