## 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],
];
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');
}
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) }}
@GRID\Source on entities for auto-configuration.Resources/views/APYDataGridBundle/.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'])
]);
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']
]);
Mass Actions:
$grid->addMassAction('delete', 'Delete', 'fa-trash', 'grid.delete');
Export:
$grid->setExport(['csv', 'xlsx']);
Pagerfanta for advanced pagination:
$source->setPagination('pagerfanta', ['itemsPerPage' => 20]);
/**
* @GRID\Source(columns="id", actions={"delete": {"ROLE_ADMIN"}})
*/
class SecureEntity {}
vendor/apy/datagrid-bundle/Resources/views/APYDataGridBundle/ to your bundle’s Resources/views/APYDataGridBundle/.Dynamic Columns:
$grid->getSource()->setColumnsCallback(function($source) {
return ['id', 'name', 'dynamic_' . date('Y')];
});
External Filters:
{{ grid_external_filter(grid) }}
Grid Manager (Multiple Grids):
$manager = $this->get('grid.manager');
$manager->addGrid('grid1', $grid1);
$manager->addGrid('grid2', $grid2);
Cache Clearing:
php bin/console cache:clear
debug:config to verify bundle registration.Deprecated Methods:
initEnvironment in Twig extensions (use initRuntime in Symfony 3+).shared="false" over scope="prototype" in services.Locale Issues:
config.yaml:
framework:
default_locale: en
grid.yml:
apy_datagrid:
locales:
fr: ['fr_FR']
ORM vs. ODM:
Doctrine\ODM\MongoDB\DocumentManager. Ensure your Source is configured correctly:
$source = new \APY\DataGridBundle\Grid\Source\Document('App\Document\Post');
Column Auto-Typing:
$grid->getSource()->setColumns([
new Column('price', 'number', ['format' => 'currency'])
]);
Enable Debug Mode:
debug: true in config/packages/apy_datagrid.yaml to log SQL queries and grid events.Check Events:
$grid->on('build.query', function($event) {
dump($event->getQuery());
});
Validate Annotations:
php bin/console debug:container --parameters to check if annotations are processed.Custom Filters:
APY\DataGridBundle\Grid\Filter\AbstractFilter:
class CustomFilter extends AbstractFilter {
public function applyFilter($query, $alias, $value) {
// Custom logic
}
}
services.yaml:
services:
App\Filter\CustomFilter:
tags:
- { name: apy_datagrid.filter, type: custom }
Custom Columns:
APY\DataGridBundle\Grid\Column\AbstractColumn for custom rendering:
class CustomColumn extends AbstractColumn {
public function renderCell($value, $row) {
return '<span class="custom">' . $value . '</span>';
}
}
Override Twig Functions:
grid() or grid_external_filter():
$twig->addFunction(new \Twig_SimpleFunction('grid', [$this, 'customGridFunction']));
Lazy Loading:
setFetchJoinStrategy('LAZY'):
$source->setFetchJoinStrategy('LAZY');
Query Optimization:
addSelect() to limit loaded fields:
$source->addSelect(['id', 'name']); // Instead of SELECT *
Avoid N+1 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
How can I help you explore Laravel packages today?