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

Datatables Bundle Laravel Package

dkomarek/datatables-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require omines/datatables-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Omines\DataTablesBundle\OminesDataTablesBundle::class => ['all' => true],
    ];
    
  2. Basic Controller Integration Create a controller with a DataTables-compatible response:

    use Omines\DataTablesBundle\DataTables;
    use Omines\DataTablesBundle\DataTables\DataTable;
    use Omines\DataTablesBundle\DataTables\LengthAwarePaginatorAdapter;
    
    #[Route('/users', name: 'users_datatable')]
    public function usersDataTable(DataTables $datatables): JsonResponse
    {
        $users = UserRepository::all(); // Your Eloquent/Doctrine query
        $adapter = new LengthAwarePaginatorAdapter($users);
        $table = $datatables->of($adapter);
    
        return $table->make(true)->json();
    }
    
  3. Frontend Setup Include DataTables CSS/JS in your Twig template:

    {{ encore_entry_link_tags('app') }}
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    

    Initialize the table:

    $(document).ready(function() {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '/users'
        });
    });
    

Implementation Patterns

Common Workflows

1. Column Customization

Use makeColumn() to define columns with custom logic:

$table = $datatables->of($adapter)
    ->addColumn('full_name', function($user) {
        return $user->first_name . ' ' . $user->last_name;
    })
    ->editColumn('active', function($user) {
        return $user->active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>';
    })
    ->make(true);

2. Filtering & Search

Leverage built-in search/filtering:

$table = $datatables->of($adapter)
    ->add('name', function($query) {
        $search = $this->getParameter('search.value');
        return $query->where('name', 'like', "%{$search}%");
    })
    ->make(true);

3. Server-Side Processing

For large datasets, use server-side processing (default):

// Controller
$table = $datatables->of($adapter)
    ->setServerSide(true)
    ->make(true);

// Frontend (already configured in JS snippet above)

4. Exporting Data

Enable CSV/Excel exports:

$table = $datatables->of($adapter)
    ->add('export', function($query) {
        return $query->select('id', 'name', 'email');
    })
    ->make(true);

Frontend:

$('#users-table').DataTable({
    // ... existing config
    dom: 'Bfrtip',
    buttons: [
        'csv', 'excel'
    ]
});

5. Integration with Forms

Use make(true) with false to render HTML (for inline editing):

$table = $datatables->of($adapter)
    ->make(false); // Returns HTML string

Render in Twig:

<div class="table-responsive">
    {{ table|raw }}
</div>

Integration Tips

Laravel-Specific Adaptations

  • Eloquent Pagination: Use LengthAwarePaginatorAdapter for Eloquent collections:
    $adapter = new LengthAwarePaginatorAdapter(User::paginate(10));
    
  • Doctrine ORM: Use DoctrinePaginatorAdapter:
    $adapter = new DoctrinePaginatorAdapter($doctrine->getRepository(User::class)->findAll());
    

Custom Adapters

Extend AbstractAdapter for custom data sources:

use Omines\DataTablesBundle\DataTables\AbstractAdapter;

class ApiAdapter extends AbstractAdapter
{
    public function getData()
    {
        $response = Http::get('https://api.example.com/users');
        return $response->json();
    }

    public function count()
    {
        return Http::get('https://api.example.com/users/count')->json()['total'];
    }
}

Twig Integration

Pass the table to Twig for dynamic rendering:

return $this->render('users/_table.html.twig', [
    'table' => $table->make(false),
]);

Gotchas and Tips

Pitfalls

1. Server-Side Processing Mismatch

  • Issue: Data doesn’t load despite serverSide: true.
  • Fix: Ensure your adapter implements count() and getData() correctly. For Eloquent, use LengthAwarePaginatorAdapter:
    $adapter = new LengthAwarePaginatorAdapter(User::query());
    

2. Column Order Discrepancy

  • Issue: Columns render out of order in the frontend.
  • Fix: Explicitly define column order in makeColumn():
    $table->addColumn('id', 'ID')
          ->addColumn('name', 'Name')
          ->addColumn('email', 'Email');
    

3. Search Not Working

  • Issue: Global search (search.value) ignores custom filters.
  • Fix: Override the search logic:
    $table->add('global_search', function($query) {
        $search = $this->getParameter('search.value');
        return $query->where(function($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('email', 'like', "%{$search}%");
        });
    });
    

4. Pagination Conflicts

  • Issue: Pagination breaks when using custom adapters.
  • Fix: Ensure count() returns the total record count, not per-page count.

Debugging Tips

1. Enable Verbose Logging

Add to config/packages/omines_datatables.yaml:

debug: true

Logs will show raw DataTables parameters and responses.

2. Inspect Request Parameters

Dump $this->getParameters() in your controller to verify DataTables sends the expected data:

dump($datatables->getParameters());

3. Frontend Debugging

Use browser DevTools to inspect:

  • Network tab: Verify AJAX requests include draw, start, length, and columns parameters.
  • Console tab: Check for JavaScript errors (e.g., missing DataTables dependencies).

Extension Points

1. Custom Responses

Override the JSON response format:

$table = $datatables->of($adapter)
    ->make(true)
    ->setResponseFormatter(function($data) {
        return [
            'data' => $data['data'],
            'meta' => [
                'total' => $data['recordsTotal'],
                'filtered' => $data['recordsFiltered'],
            ],
        ];
    });

2. Event Listeners

Listen to DataTables events (e.g., preDraw, draw):

$('#users-table').on('preDraw', function() {
    console.log('Table about to redraw');
});

3. Dynamic Column Rendering

Use Twig functions to render columns dynamically:

{#
    In your Twig template:
#}
{% macro renderCell(value, row) %}
    {% if row.active %}
        <span class="badge badge-success">Active</span>
    {% else %}
        <span class="badge badge-danger">Inactive</span>
    {% endif %}
{% endmacro %}

4. API Versioning

For Symfony API Platform, combine with ApiPlatformBundle:

use Omines\DataTablesBundle\DataTables\ApiPlatformAdapter;

$adapter = new ApiPlatformAdapter($context->getCollectionOperation());
$table = $datatables->of($adapter)->make(true);

5. Performance Optimization

  • Lazy Loading: Use ->setServerSide(true) for large datasets.
  • Selective Columns: Fetch only needed columns in add():
    $table->add('export', function($query) {
        return $query->select('id', 'name'); // Only fetch these columns
    });
    
  • Caching: Cache adapter responses if data rarely changes:
    $adapter = new CachedAdapter($originalAdapter, new FilesystemCache());
    
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