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

artscorestudio/datagrid-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

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

Enable the bundle in config/bundles.php:

return [
    // ...
    APY\DataGridBundle\APYDataGridBundle::class => ['all' => true],
];
  1. Basic Controller Usage:

    use APY\DataGridBundle\Grid\Source\Entity;
    use APY\DataGridBundle\Grid\Grid;
    
    public function gridAction(Grid $grid)
    {
        $source = new Entity('App\Entity\YourEntity');
        $grid->setSource($source);
        return $grid->getGridResponse('AppBundle::grid.html.twig');
    }
    
  2. First Use Case: Display a sortable/filterable grid of User entities with default columns (id, name, email):

    $source = new Entity('App\Entity\User');
    $grid->setSource($source);
    

    Render in Twig:

    {{ grid(grid) }}
    

Key Starting Points

  • Documentation: Summary.md
  • Annotations: Use @GRID\Source on entities for auto-configuration.
  • Twig Extensions: Override templates via Resources/views/APYDataGridBundle/.

Implementation Patterns

Common Workflows

  1. Entity-Based Grids:

    // Auto-detect columns from Doctrine metadata
    $source = new Entity('App\Entity\Product');
    $grid->setSource($source);
    
    // Customize columns
    $grid->getSource()->setColumns([
        'id', 'name', 'price',
        new Column('createdAt', 'Date', ['format' => 'Y-m-d'])
    ]);
    
  2. Filtering:

    // Add a text filter for 'name'
    $grid->getSource()->addFilter('name', 'text', 'Contains');
    
    // Add a select filter with predefined options
    $grid->getSource()->addFilter('status', 'select', [
        'options' => ['active' => 'Active', 'inactive' => 'Inactive']
    ]);
    
  3. Mass Actions:

    $grid->addMassAction('delete', 'Delete', 'fa-trash', 'grid.delete');
    
  4. Export:

    $grid->setExport(['csv', 'xlsx']);
    

Integration Tips

  • Pagination: Use Pagerfanta for advanced pagination:
    $source->setPagination('pagerfanta', ['itemsPerPage' => 20]);
    
  • Security: Restrict columns/actions via annotations:
    /**
     * @GRID\Source(columns="id", actions={"delete": {"ROLE_ADMIN"}})
     */
    class SecureEntity {}
    
  • Templates: Override Twig templates by copying from: vendor/apy/datagrid-bundle/Resources/views/APYDataGridBundle/ to your bundle’s Resources/views/APYDataGridBundle/.

Advanced Patterns

  1. Dynamic Columns:

    $grid->getSource()->setColumnsCallback(function($source) {
        return ['id', 'name', 'dynamic_' . date('Y')];
    });
    
  2. External Filters:

    {{ grid_external_filter(grid) }}
    
  3. Grid Manager (Multiple Grids):

    $manager = $this->get('grid.manager');
    $manager->addGrid('grid1', $grid1);
    $manager->addGrid('grid2', $grid2);
    

Gotchas and Tips

Pitfalls

  1. Cache Clearing:

    • After adding annotations or templates, clear the cache:
      php bin/console cache:clear
      
    • Use debug:config to verify bundle registration.
  2. Deprecated Methods:

    • Avoid initEnvironment in Twig extensions (use initRuntime in Symfony 3+).
    • Prefer shared="false" over scope="prototype" in services.
  3. Locale Issues:

    • Ensure locale is set in config.yaml:
      framework:
          default_locale: en
      
    • For custom locales, configure in grid.yml:
      apy_datagrid:
          locales:
              fr: ['fr_FR']
      
  4. ORM vs. ODM:

    • ODM sources require Doctrine\ODM\MongoDB\DocumentManager. Ensure your Source is configured correctly:
      $source = new \APY\DataGridBundle\Grid\Source\Document('App\Document\Post');
      
  5. Column Auto-Typing:

    • If columns aren’t auto-typed correctly, explicitly define them:
      $grid->getSource()->setColumns([
          new Column('price', 'number', ['format' => 'currency'])
      ]);
      

Debugging Tips

  1. Enable Debug Mode:

    • Set debug: true in config/packages/apy_datagrid.yaml to log SQL queries and grid events.
  2. Check Events:

    • Listen to grid events for debugging:
      $grid->on('build.query', function($event) {
          dump($event->getQuery());
      });
      
  3. Validate Annotations:

    • Use php bin/console debug:container --parameters to check if annotations are processed.

Extension Points

  1. Custom Filters:

    • Create a filter class extending APY\DataGridBundle\Grid\Filter\AbstractFilter:
      class CustomFilter extends AbstractFilter {
          public function applyFilter($query, $alias, $value) {
              // Custom logic
          }
      }
      
    • Register it in services.yaml:
      services:
          App\Filter\CustomFilter:
              tags:
                  - { name: apy_datagrid.filter, type: custom }
      
  2. Custom Columns:

    • Extend APY\DataGridBundle\Grid\Column\AbstractColumn for custom rendering:
      class CustomColumn extends AbstractColumn {
          public function renderCell($value, $row) {
              return '<span class="custom">' . $value . '</span>';
          }
      }
      
  3. Override Twig Functions:

    • Extend the Twig environment in your bundle to override grid() or grid_external_filter():
      $twig->addFunction(new \Twig_SimpleFunction('grid', [$this, 'customGridFunction']));
      

Performance Tips

  1. Lazy Loading:

    • For large datasets, use setFetchJoinStrategy('LAZY'):
      $source->setFetchJoinStrategy('LAZY');
      
  2. Query Optimization:

    • Use addSelect() to limit loaded fields:
      $source->addSelect(['id', 'name']); // Instead of SELECT *
      
  3. Avoid N+1 Queries:

    • Enable DQL logging to identify queries:
      doctrine:
          dbal:
              logging: true
      

```markdown
### Configuration Quirks
1. **`grid.yml` Overrides**:
   - Global configurations (e.g., default export formats) must be set in `config/packages/apy_datagrid.yaml`:
     ```yaml
     apy_datagrid:
         default_export_formats: ['csv', 'xlsx']
         default_items_per_page: 50
     ```

2. **Annotation vs. YAML**:
   - Annotations take precedence over YAML configurations. Use YAML for global defaults and annotations for entity-specific overrides.

3. **Security Roles**:
   - Roles are case-sensitive. Ensure roles in annotations match Symfony’s security roles:
     ```php
     /**
      * @GRID\Source(actions={"delete": {"ROLE_ADMIN"}})
      */
     ```

4. **Twig Auto-Reloading**:
   - If Twig templates aren’t updating, clear the cache or restart the dev server:
     ```bash
     php bin/console cache:clear && symfony-server-start
     ```

### Pro Tips
1. **Reuse Grids**:
   - Create a base grid class to avoid repetition:
     ```php
     class BaseGrid {
         public function buildGrid(Grid $grid) {
             $grid->setSource(new Entity('App\Entity\BaseEntity'));
             $grid->addMassAction('export', 'Export', 'fa-file-excel');
         }
     }
     ```

2. **Dynamic Source Switching**:
   - Switch between ORM/ODM/Array sources dynamically:
     ```php
     if ($useOdm) {
         $source = new Document('App\Document\Post');
     } else {
         $source = new Entity('App\Entity\Post');
     }
     $grid->setSource($source);
     ```

3. **Localization**:
   - Use the `trans` filter
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky