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

edweld/datatablesbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sg/datatablesbundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Stwe\DatatablesBundle\StweDatatablesBundle::class => ['all' => true],
    ];
    
  2. Basic Controller Integration:

    use Stwe\DatatablesBundle\DataTablesController;
    use Stwe\DatatablesBundle\DataTablesFactory;
    
    class UserController extends DataTablesController
    {
        public function userTableAction(DataTablesFactory $factory)
        {
            return $this->createDataTableResponse($factory->create()
                ->add('id', 'column')
                ->add('name', 'column')
                ->add('email', 'column')
                ->setDataSource($this->getDoctrine()->getRepository('App:User')->findAll())
            );
        }
    }
    
  3. First Use Case: Render a table in a Twig template:

    {{ render(controller('App\Controller\UserController::userTableAction')) }}
    

Implementation Patterns

Workflows

  1. Repository Integration: Use Doctrine repositories as data sources:

    $factory->create()
        ->setDataSource($this->getDoctrine()->getRepository('App:User')->findAll())
        ->add('username', 'column', ['title' => 'Username']);
    
  2. Column Customization:

    • Basic Columns:
      $this->columnBuilder->add('id', 'column', ['title' => 'ID']);
      
    • Action Columns (e.g., edit/delete buttons):
      $this->columnBuilder->add('actions', 'action', [
          'title' => 'Actions',
          'actions' => [
              'edit' => ['route' => 'edit_user', 'params' => ['id' => 'id']],
              'delete' => ['route' => 'delete_user', 'params' => ['id' => 'id']],
          ],
      ]);
      
  3. Server-Side Processing: Enable server-side processing for large datasets:

    $factory->create()
        ->setServerSide(true)
        ->setDataSource($this->getDoctrine()->getRepository('App:User')->findAll());
    
  4. Pagination and Sorting: Leverage built-in support:

    $factory->create()
        ->setDefaultSort(['column' => 'name', 'dir' => 'asc'])
        ->setDefaultLength(10);
    
  5. Twig Integration: Use render in templates or embed via:

    {% datatables_table table %}
    

Integration Tips

  • Routing: Define routes for DataTables endpoints:
    # config/routes.yaml
    user_table:
        path: /user/table
        controller: App\Controller\UserController::userTableAction
    
  • Asset Management: Ensure jQuery and DataTables JS/CSS are included in your base template:
    {{ encore_entry_link_tags('app') }}
    {{ encore_entry_script_tags('app') }}
    
  • Custom Templates: Override default templates by copying from: vendor/stwe/datatables-bundle/Resources/views/.

Gotchas and Tips

Pitfalls

  1. CORS Issues: If using AJAX with server-side processing, ensure CORS headers are configured for cross-origin requests.

    // In a controller or event subscriber
    $response->headers->set('Access-Control-Allow-Origin', '*');
    
  2. Doctrine QueryBuilder Limitation: Server-side processing may fail if the underlying query doesn’t support COUNT(*) or LIMIT/OFFSET. Use raw SQL or hydrate to arrays if needed:

    $queryBuilder->select('u.id, u.name, u.email');
    
  3. Column Naming Conflicts: Avoid column names that conflict with DataTables reserved keywords (e.g., order, search).

  4. Pagination Overhead: Server-side processing with large datasets can be resource-intensive. Optimize queries with indexes and avoid SELECT *.


Debugging

  1. Enable Debug Mode: Set debug: true in config/packages/stwe_datatables.yaml to log DataTables requests:

    stwe_datatables:
        debug: true
    
  2. Check Network Requests: Use browser dev tools to inspect AJAX payloads and responses for misconfigurations.

  3. Validate JSON Responses: Ensure responses match DataTables expected format:

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

Extension Points

  1. Custom Columns: Extend the bundle by creating custom column types:

    namespace App\DataTables\Column;
    
    use Stwe\DatatablesBundle\Column\AbstractColumn;
    
    class CustomColumn extends AbstractColumn
    {
        public function render($row)
        {
            return '<span class="custom-class">' . $row['value'] . '</span>';
        }
    }
    

    Register in services.yaml:

    services:
        App\DataTables\Column\CustomColumn:
            tags: ['stwe.datatables.column_type']
    
  2. Event Listeners: Subscribe to DataTables events (e.g., datatables.build.query) to modify queries dynamically:

    use Stwe\DatatablesBundle\Event\BuildQueryEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class DataTablesSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                BuildQueryEvent::NAME => 'onBuildQuery',
            ];
        }
    
        public function onBuildQuery(BuildQueryEvent $event)
        {
            $event->getQueryBuilder()->andWhere('u.active = 1');
        }
    }
    
  3. Configuration Overrides: Override default settings in config/packages/stwe_datatables.yaml:

    stwe_datatables:
        default_options:
            processing: true
            server_side: true
            ajax:
                url: '/api/datatables'
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware