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

Data Tables Generator Bundle Laravel Package

brown298/data-tables-generator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require brown298/data-tables-generator-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Brown298\DataTablesGeneratorBundle\Brown298DataTablesGeneratorBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Publish the default config (if needed) and adjust in config/packages/brown298_data_tables_generator.yaml:

    brown298_data_tables_generator:
        default_options: ~ # Override defaults here
    
  3. First Use Case: Rendering a Table Use the DataTablesGenerator service in a controller:

    use Brown298\DataTablesGeneratorBundle\DataTablesGenerator;
    
    public function index(DataTablesGenerator $generator)
    {
        $data = [
            ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'],
            ['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com'],
        ];
    
        return $generator->generate($data, [
            'columns' => [
                ['data' => 'id', 'title' => 'ID'],
                ['data' => 'name', 'title' => 'Name'],
                ['data' => 'email', 'title' => 'Email'],
            ],
        ]);
    }
    
  4. Twig Integration Render the output in a Twig template:

    {{ include('Brown298DataTablesGeneratorBundle::table.html.twig', {
        table: table
    }) }}
    

Implementation Patterns

Common Workflows

1. Server-Side Processing

Use generate() with serverSide: true for large datasets:

$generator->generate($data, [
    'serverSide' => true,
    'columns' => [...],
    'ajax' => [
        'url' => $this->generateUrl('api_datatable'),
        'type' => 'POST',
    ],
]);

2. Dynamic Column Configuration

Fetch columns from a Doctrine entity or DTO:

$columns = [];
foreach ($entity->getMetadata()->getFieldNames() as $field) {
    $columns[] = ['data' => $field, 'title' => ucfirst($field)];
}

3. Custom Rendering

Override Twig templates by copying from:

vendor/brown298/data-tables-generator-bundle/Resources/views/

to:

templates/bundles/brown298datatablesgenerator/

4. Integration with Forms

Combine with Symfony Forms for editable tables:

$formFactory = $this->get('form.factory');
$form = $formFactory->createBuilder()
    ->add('name', TextType::class)
    ->add('email', EmailType::class)
    ->getForm();

$generator->generate($data, [
    'columns' => [
        ['data' => 'id', 'title' => 'ID'],
        ['data' => 'name', 'title' => 'Name', 'render' => function($value, $row) use ($formFactory) {
            return $formFactory->createNamed('edit_name', TextType::class, $row['name'])->render();
        }],
    ],
]);

5. API-Driven Tables

Use generate() with ajax options for SPAs:

return $generator->generate($data, [
    'ajax' => [
        'url' => '/api/table-data',
        'dataSrc' => '',
    ],
    'processing' => true,
]);

Integration Tips

Symfony Events

Listen to datatables.generator.init to modify options globally:

$eventDispatcher->addListener('datatables.generator.init', function($event) {
    $event->setOptions(array_merge($event->getOptions(), [
        'language' => ['url' => '/locales/datatables.json'],
    ]));
});

Doctrine QueryBuilder Support

Use Brown298\DataTablesGeneratorBundle\QueryBuilder\DataTablesQueryBuilder for server-side filtering/sorting:

$qb = $this->createQueryBuilder('u');
$generator->applyDataTables($qb, $request);
$data = $qb->getQuery()->getResult();

Custom Data Sources

Extend Brown298\DataTablesGeneratorBundle\DataTablesGenerator:

class CustomGenerator extends DataTablesGenerator
{
    public function generateCustom($data, array $options)
    {
        // Custom logic
        return parent::generate($data, $options);
    }
}

Register as a service:

services:
    custom.datatables.generator:
        class: App\CustomGenerator
        tags: ['datatables.generator']

Gotchas and Tips

Pitfalls

  1. Server-Side vs. Client-Side

    • Issue: Forgetting serverSide: true causes all data to load client-side, breaking pagination/sorting for large datasets.
    • Fix: Always use server-side processing for datasets > 100 rows.
  2. Column Data Mismatch

    • Issue: data in columns must match keys in your data array/object.
    • Fix: Validate with array_keys($data[0]) or get_class_methods($entity).
  3. Twig Template Overrides

    • Issue: Custom templates not loading due to incorrect path.
    • Fix: Ensure templates are in templates/bundles/brown298datatablesgenerator/ and named exactly (e.g., table.html.twig).
  4. CORS for AJAX

    • Issue: AJAX requests fail with CORS errors.
    • Fix: Configure Symfony’s CORS bundle or add headers in your API route:
      $response->headers->set('Access-Control-Allow-Origin', '*');
      
  5. Doctrine Lazy Loading

    • Issue: QueryBuilder throws LazyLoadingException if entities aren’t fully loaded.
    • Fix: Use DISTINCT or fetch related entities eagerly:
      $qb->select('DISTINCT u');
      $qb->leftJoin('u.profile', 'p')->addSelect('p');
      

Debugging Tips

  1. Dump Options Log the final options to debug:

    $options = $generator->getOptions($request, $defaultOptions);
    \Symfony\Component\Debug\Debug::dump($options);
    
  2. Check Request Data For server-side processing, inspect the incoming request:

    $requestData = json_decode($request->getContent(), true);
    \Symfony\Component\Debug\Debug::dump($requestData);
    
  3. Validate JSON Output Ensure the generator returns valid JSON for AJAX:

    $response = new JsonResponse($generator->generate(...));
    $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);
    

Configuration Quirks

  1. Default Options

    • Override globally in config/packages/brown298_data_tables_generator.yaml:
      brown298_data_tables_generator:
          default_options:
              serverSide: true
              processing: true
              language:
                  url: '/locales/datatables.json'
      
  2. Language Files

    • Place custom language files in public/locales/ and reference:
      'language' => ['url' => '/locales/datatables_custom.json']
      
  3. Column Callbacks

    • Use render for custom cell rendering, but ensure callbacks are serializable if used in AJAX:
      'columns' => [
          ['data' => 'status', 'render' => function($value) {
              return $value === 'active' ? '<span class="label label-success">Active</span>' : 'Inactive';
          }],
      ]
      

Extension Points

  1. Custom DataTables Version Override the included DataTables JS/CSS by extending the bundle’s assets:

    # config/packages/twig.yaml
    twig:
        paths:
            '%kernel.project_dir%/templates/bundles/brown298datatablesgenerator/assets':
                prefix: 'bundles/brown298datatablesgenerator/assets'
    
  2. Event Listeners Subscribe to datatables.generator.post_generate to modify the final output:

    $eventDispatcher->addListener('datatables.generator.post_generate', function($event) {
        $event->setTableData(array_map(function($row) {
            $row['custom_field'] = 'added_via_listener';
            return $row;
        }, $event->getTable
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
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