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

apymakoso/datagrid-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require apymakoso/datagrid-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        APY\DataGridBundle\APYDataGridBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Create a basic grid for an entity in a controller:

    use APY\DataGridBundle\Grid\Source\Entity;
    
    public function indexAction()
    {
        $source = new Entity('App\Entity\Product');
        $grid = $this->get('grid');
        $grid->setSource($source);
        return $grid->getGridResponse('App:product_grid.html.twig');
    }
    
  3. Template:

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

    php bin/console cache:clear
    

Key Files to Review

  • Resources/doc/summary.md (Core documentation)
  • Resources/doc/grid_configuration/ (Examples and templates)
  • Resources/views/ (Default Twig templates)

Implementation Patterns

Common Workflows

1. Entity-Based Grid

// Controller
$source = new Entity('App\Entity\User');
$source->setUseRepositoryMethod(true); // Use custom repository method
$source->setRepositoryMethod('findAllActive'); // e.g., UserRepository::findAllActive()

$grid = $this->get('grid');
$grid->setSource($source);
$grid->setTitle('User Management');
return $grid->getGridResponse('App:user_grid.html.twig');

2. Custom Column Configuration

// In your entity or via YAML/XML
/**
 * @GRID\Column(
 *     title="Full Name",
 *     type="text",
 *     width="200px",
 *     align="left",
 *     sortable=true,
 *     filterable=true,
 *     template="App:Grid/columns/name.html.twig"
 * )
 */
protected $fullName;

3. Filtering

// Controller (dynamic filters)
$grid->getSource()->addFilter('status', 'eq', 'active');

// Twig (external filter box)
{{ grid_filter_box(grid) }}

4. Mass Actions

// Controller
$grid->addMassAction('delete', 'Delete', 'fa-trash', 'grid.delete', ['confirm' => true]);
$grid->addMassAction('export', 'Export to CSV', 'fa-file-excel-o', 'grid.export_csv');

// Twig
{{ grid_mass_actions(grid) }}

5. Export

// Controller (auto-export)
$grid->setExport(true);
$grid->setExportFormats(['csv', 'xlsx']);

// Manual export
$export = $grid->getExport();
$export->setFormat('csv');
return $export->getResponse('user_export.csv');

6. Ajax Loading

// Controller
$grid->setAjax(true);
$grid->setAjaxUrl($this->generateUrl('app_user_grid_ajax'));

// Twig
{{ grid_ajax(grid) }}

7. Security Roles

// Controller
$grid->setAccessControl([
    'column' => ['id' => 'ROLE_ADMIN'],
    'action' => ['delete' => 'ROLE_SUPER_ADMIN'],
]);

Integration Tips

With Doctrine

  • Use Entity source for ORM entities.
  • Leverage setRepositoryMethod() for custom queries.
  • Map fields with @GRID\Column or @GRID\Source annotations.

With MongoDB (ODM)

  • Use Document source for MongoDB documents.
  • Configure groups for nested documents:
    $source = new Document('App\Document\Product');
    $source->setGroups(['category' => ['name', 'description']]);
    

With Arrays (Vector Source)

$source = new Vector($yourArrayData);
$grid->setSource($source);

Custom Templates

  • Override Twig templates in templates/App/Grid/.
  • Example: columns/name.html.twig for custom column rendering.

Pagination

  • Default: Uses Knp\Component\Pagerfanta\Paginator.
  • Configure via:
    $grid->setItemsPerPage(20);
    $grid->setMaxItemsPerPage(100);
    

Localization

  • Set locale in Twig:
    {% trans_default_domain 'APYDataGridBundle' %}
    {{ grid(grid) }}
    
  • Configure number/date formats in config/packages/apy_datagrid.yaml:
    apy_datagrid:
        locale: 'fr_FR'
        number_formats:
            currency: '€ #,##0.00'
    

Gotchas and Tips

Pitfalls

  1. Cache Issues:

    • Always clear cache after adding/updating annotations or YAML/XML configs.
    • Use php bin/console cache:clear --env=prod in production.
  2. Annotation Parsing:

    • Ensure annotations are on the entity class, not properties, for @GRID\Source.
    • Use use APY\DataGridBundle\Grid\Mapping as GRID; in imports.
  3. Doctrine Proxy Classes:

    • Avoid using proxy objects directly in filters/columns. Use DQL or custom repository methods instead.
  4. Ajax Conflicts:

    • Ensure your Ajax URL points to a controller that returns only the grid data (not a full response).
    • Example:
      public function ajaxAction()
      {
          $grid = $this->get('grid');
          return $grid->getAjaxResponse();
      }
      
  5. Export Quirks:

    • PDF export requires mikehaertl/php-excel and dompdf/dompdf.
    • CSV/Excel exports may fail if column data types are incompatible (e.g., dates in CSV).
  6. Security:

    • Always set access_control for sensitive actions/columns.
    • Test with ROLE_USER and ROLE_ADMIN to avoid accidental exposure.
  7. Performance:

    • Avoid loading all columns by default. Use setDefaultColumns():
      $grid->setDefaultColumns(['id', 'name', 'createdAt']);
      
    • For large datasets, use setUseRepositoryMethod(true) with a paginated query.
  8. Locale Mismatches:

    • Ensure your Twig templates and Symfony locale settings match the grid’s locale.
    • Debug with {{ dump(grid.getSource().getLocale()) }}.

Debugging Tips

  1. Enable Debug Mode:

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

    • Listen for events to debug filtering/sorting:
      $grid->on('pre_build_query', function ($event) {
          $query = $event->getQuery();
          // Log or inspect $query
      });
      
  3. Inspect Source Data:

    • Dump the source data in a controller:
      $data = $grid->getSource()->getData();
      dump($data);
      
  4. Validate Annotations:

    • Use php bin/console debug:container APY\DataGridBundle\Annotation\Driver to check if annotations are loaded.
  5. Twig Debugging:

    • Override templates and add {{ dump(grid) }} to inspect the grid object.

Extension Points

  1. Custom Sources:

    • Extend APY\DataGridBundle\Grid\Source\AbstractSource for new data sources (e.g., API, Elasticsearch).
  2. Custom Columns:

    • Create a class extending APY\DataGridBundle\Grid\Column\AbstractColumn:
      class CustomColumn extends AbstractColumn
      {
          public function getValue($item)
          {
              return $item->getCustomValue();
          }
      }
      
    • Register it in services.yaml:
      services:
          App\Grid\Column\CustomColumn:
              tags:
                  - { name: apy_datagrid.column_type, type: custom }
      
  3. Custom Filters:

    • Extend APY\DataGridBundle\Grid\Filter\AbstractFilter:
      class CustomFilter extends AbstractFilter
      {
          public function apply($queryBuilder, $alias, $direction)
          {
              // Custom logic
          }
      }
      
    • Tag it in services.yaml:
      tags:
          - { name: apy_datagrid.filter_type, type: custom }
      
  4. Event Subscribers:

    • Listen to grid events for pre/post-processing:
      $grid->on('pre_build_query', [$this, 'on
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui