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

Datatablesbundle Laravel Package

allsetlu/datatablesbundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the Bundle**
   ```bash
   composer require allsetlu/datatablesbundle

Enable in config/bundles.php:

return [
    // ...
    Stwe\DatatablesBundle\StweDatatablesBundle::class => ['all' => true],
];
  1. Configure the Bundle Add to config/packages/stwe_datatables.yaml:

    stwe_datatables:
        # Default options (optional)
        default_options:
            order: [[0, 'asc']]
            page_length: 10
    
  2. First Use Case: Basic Entity Table Create a controller action to handle DataTables requests:

    use Stwe\DatatablesBundle\DataTablesController;
    use Stwe\DatatablesBundle\DataTablesFactory;
    use Stwe\DatatablesBundle\DataTables;
    
    class UserController extends AbstractController
    {
        public function datatableAction(DataTablesFactory $factory, EntityManagerInterface $em)
        {
            $dataTables = $factory->create(DataTables::class);
            $dataTables->setEntityManager($em)
                       ->setEntityClass(User::class)
                       ->setSearchableFields(['username', 'email'])
                       ->setOrderableFields(['id', 'username', 'createdAt']);
    
            return $dataTables->getResponse();
        }
    }
    
  3. Twig Template Integration Add DataTables JS/CSS assets to your base template:

    {{ encore_entry_link_tags('app') }}
    {{ stwe_datatables_js() }}
    {{ stwe_datatables_css() }}
    

    Render a table in Twig:

    <table id="users-table" class="table table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $('#users-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{{ path('app_user_datatable') }}'
            });
        });
    </script>
    

Implementation Patterns

Common Workflows

1. CRUD Operations with DataTables

  • Create: Use setCreateUrl() to point to a form endpoint.
  • Edit/Delete: Add action buttons in columns:
    $dataTables->setColumns([
        'id' => ['title' => 'ID'],
        'username' => ['title' => 'Username'],
        'actions' => [
            'title' => 'Actions',
            'render' => function($data) {
                return '<a href="' . url('edit', ['id' => $data['id']]) . '">Edit</a> ' .
                       '<a href="' . url('delete', ['id' => $data['id']]) . '">Delete</a>';
            }
        ]
    ]);
    

2. Custom Query Logic

Extend the query builder with custom logic:

$dataTables->addCallback('queryBuilder', function($queryBuilder, $dataTables) {
    if ($dataTables->getRequest()->query->get('status')) {
        $queryBuilder->andWhere('u.status = :status')
                     ->setParameter('status', $dataTables->getRequest()->query->get('status'));
    }
});

3. Dynamic Columns

Fetch columns dynamically from the entity metadata:

$dataTables->setColumnsFromEntity(User::class, [
    'exclude' => ['password', 'apiToken']
]);

4. Integration with Forms

Use setForm() to bind DataTables to a Symfony form:

$form = $this->createForm(UserType::class);
$dataTables->setForm($form);

5. Pagination and Sorting

Configure default behavior:

# config/packages/stwe_datatables.yaml
stwe_datatables:
    default_options:
        page_length: 25
        server_side: true
        processing: true

Integration Tips

With API Platform

Use setSerializer() to customize serialization:

$dataTables->setSerializer(new CustomSerializer());

With VichUploaderBundle

Handle file columns by overriding the getValue() method:

$dataTables->addCallback('getValue', function($value, $column, $data) {
    if ($column === 'avatar' && $value) {
        return '<img src="' . asset($value->getUrl()) . '" width="50">';
    }
    return $value;
});

With FOSUserBundle

Extend the user entity table:

$dataTables->setEntityClass(User::class)
           ->setSearchableFields(['username', 'email', 'firstName', 'lastName'])
           ->setOrderableFields(['username', 'lastName', 'createdAt']);

With AJAX Loading

Use setAjaxUrl() for dynamic table loading:

$dataTables->setAjaxUrl($this->generateUrl('app_user_datatable'));

Gotchas and Tips

Pitfalls

  1. PostgreSQL Limitations

    • Avoid using this bundle with PostgreSQL (unsupported by maintainer).
    • Workaround: Fork the bundle or use a different package like youshido/DoctrineExtensions for PostgreSQL-specific features.
  2. Memory Issues with Large Datasets

    • DataTables loads all data into memory during server-side processing.
    • Fix: Use setPageLength() to limit rows per page or implement cursor-based pagination.
  3. Caching Headaches

    • DataTables requests may bypass Symfony cache if not configured properly.
    • Fix: Ensure stwe_datatables.cache is enabled in config:
      stwe_datatables:
          cache: true
      
  4. CSRF Token Mismatch

    • Server-side requests may fail due to missing CSRF tokens.
    • Fix: Disable CSRF for DataTables routes:
      # config/packages/security.yaml
      access_control:
          - { path: ^/datatables, roles: PUBLIC_ACCESS }
      
  5. JavaScript Conflicts

    • DataTables may conflict with other jQuery plugins.
    • Fix: Use noConflict mode:
      var $j = jQuery.noConflict();
      $j(document).ready(function() {
          $j('#table').DataTable({ ... });
      });
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/dev/stwe_datatables.yaml:

    stwe_datatables:
        debug: true
    
  2. Inspect Raw DataTables Requests Dump the request object in your controller:

    dump($dataTables->getRequest()->query->all());
    
  3. Check SQL Queries Enable Doctrine debugging:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  4. Validate JSON Responses Ensure responses match DataTables expected format:

    {
        "draw": 1,
        "recordsTotal": 100,
        "recordsFiltered": 50,
        "data": [...]
    }
    

Extension Points

  1. Custom Response Transformers Override the response format:

    $dataTables->addCallback('transformResponse', function($response) {
        $response['custom_field'] = 'value';
        return $response;
    });
    
  2. Event Subscribers Listen to DataTables events:

    use Stwe\DatatablesBundle\Event\DataTablesEvent;
    
    public function onDataTablesBuildQuery(DataTablesEvent $event)
    {
        $event->getDataTables()->addCallback('queryBuilder', function($qb) {
            $qb->andWhere('u.deleted_at IS NULL');
        });
    }
    
  3. Custom Column Types Extend column rendering:

    $dataTables->setColumns([
        'status' => [
            'title' => 'Status',
            'render' => function($data) {
                return '<span class="badge ' . ($data['status'] ? 'badge-success' : 'badge-danger') . '">' . $data['status'] . '</span>';
            }
        ]
    ]);
    
  4. Integration with API Platform Use setPagination() for API-style pagination:

    $dataTables->setPagination('custom', function($page, $limit) {
        return [
            'page' => $page,
            'limit' => $limit,
            '_format' => 'json'
        ];
    });
    
  5. Localization Override translations:

    # config/packages/stwe_d
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager