yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.76k stars 857 forks source link

Handle DateTime values better #3156

Closed miken32 closed 3 months ago

miken32 commented 4 months ago

Summary of problem or feature request

In the Helper::transformRow() method there is special code for nicely formatting a DateTime object into a string value. However, "processing" is done before "transforming" so the Helper::convertToArray() method has already converted all DateTimes into arrays.

Code snippet of problem

$data = [["a_date" => new DateTime()], ["a_date" => new DateTime('tomorrow')]];
$table = Yajra\DataTables\Facades\DataTables::collection($data)->make();
dump($table);

This results in something like this:

= Illuminate\Http\JsonResponse {#6936
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#6935},
    +original: [
      "draw" => 0,
      "recordsTotal" => 2,
      "recordsFiltered" => 2,
      "data" => [
        [
          "a_date" => [
            "date" => "2024-07-05 17:06:52.608468",
            "timezone_type" => 3,
            "timezone" => "America/Toronto",
          ],
        ],
        [
          "a_date" => [
            "date" => "2024-07-06 00:00:00.000000",
            "timezone_type" => 3,
            "timezone" => "America/Toronto",
          ],
        ],
      ],
      "input" => [],
    ],
    +exception: null,
  }

Where I think the intent (based on the code in Helper::transformRow()) is something like this:

= Illuminate\Http\JsonResponse {#6936
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#6935},
    +original: [
      "draw" => 0,
      "recordsTotal" => 2,
      "recordsFiltered" => 2,
      "data" => [
        [
          "a_date" => "2024-07-05 17:06:52",
        ],
        [
          "a_date" => "2024-07-06 00:00:00",
        ],
      ],
      "input" => [],
    ],
    +exception: null,
  }

System details

yajra commented 4 months ago

Yes correct, this was the intention and behavior in the previous versions. Thank you for digging into the details.

If you can, please do not hesitate to submit a PR. Thanks!

miken32 commented 3 months ago

PR submitted. I wanted to check and see when this behaviour changed and it looks like the array return is present in versions 10 and 9, but I couldn't test any earlier due to PHP version incompatibilities. So it has been like that for a while; I'll leave it to you to decide if there's a possibility of this change being disruptive.