peace_love
peace_love

Reputation: 6471

How can I use datatables with data object?

I am generating a json file to use it later in my datatables:

$data = $serializer->serialize($table, 'json');
$file = 'data/data.json';
file_put_contents($file, $data);

The integration into my datatable:

var table = $('.table').DataTable({
    "ajax": {
      "url": "{{ absolute_url(asset('data/data.json')) }}",
      "dataSrc": ""
    },

Is it possible instead of creating a file, use the data object directly?

Upvotes: 0

Views: 493

Answers (2)

SilvioQ
SilvioQ

Reputation: 2072

Yes ... you can use data option in your javascript, like this ... Check https://datatables.net/examples/data_sources/js_array.html

<?php
// controller
   return $this->render("myTemplate.html.twig", ["data" => $data]);

and your template will look ...

var table = $('.table').DataTable({
    "data": {{ data|json_encode|raw }},
    "columns": [
        ....
    ]

Update

Since you use special serializer, your code will look

<?php
// controller
   $data = $serializer->serialize($table, 'json');
   return $this->render("myTemplate.html.twig", ["data" => $data]);

and your twig template must be ...

  var table = $('.table').DataTable({
    "data": {{ data|raw }},
    "columns": [
      {% for key, value in columns %}
       { "data": "id"},
      {% endfor %}

    ]
  });

Upvotes: 1

i.am.michiel
i.am.michiel

Reputation: 10404

Yes, it is.

  1. Create a route that responds to data/data.json
my_data_route_name:
    path: /data/data.json
    controller: App\YourController::yourAction
  1. Generate your JSON data
$data = []; // Get your data

// You can serialize it and return a Response with the content-type
$json = $serializer->serialize($data, 'json');
return new Response($json, 200, [
    'content-type' => 'application/json'
]);

// or let the symfony serializer handle it.
return $this->json($data);

Upvotes: 1

Related Questions