n1crack / datatables

Simplify your Datatables server-side processing effortlessly using our lightning-fast PHP library, streamlining your workflow seamlessly.
https://datatables.ozdemir.be/
MIT License
267 stars 90 forks source link

data as array are forbidden #90

Open xJuvi opened 1 year ago

xJuvi commented 1 year ago

In some cases it's useful to define a single dataset as array, f.e. if you want to order by an id bis display a human readeble name.

One example which i tried with server-side rendering is here: https://datatables.net/manual/data/orthogonal-data#Predefined-values

Is it possible to change it' I first look into the source code i think there are much changes required. If i try to define data as array i get an exception:

Fatal error: Uncaught TypeError: Return value of Ozdemir\Datatables\Column::value() must be of the type string, array returned in /var/www/vhosts/httpdocs/wwwroot/vendor/ozdemir/datatables/src/Column.php:75 Stack trace: #0 /var/www/vhosts/httpdocs/wwwroot/vendor/ozdemir/datatables/src/Datatables.php(219): Ozdemir\Datatables\Column->value(Array) #1 [internal function]: Ozdemir\Datatables\Datatables->Ozdemir\Datatables\{closure}(Object(Ozdemir\Datatables\Column)) #2 /var/www/vhosts/httpdocs/wwwroot/vendor/ozdemir/datatables/src/Datatables.php(220): array_map(Object(Closure), Array) #3 [internal function]: Ozdemir\Datatables\Datatables->prepareRowData(Array) #4 /var/www/vhosts/httpdocs/wwwroot/vendor/ozdemir/datatables/src/Datatables.php(207): array_map(Array, Array) #5 /var/www/vhosts/httpdocs/wwwroot in /var/www/vhosts/httpdocs/wwwroot/vendor/ozdemir/datatables/src/Column.php on line 75
moudarir commented 3 months ago

+1

Below another use case in ->edit() method. I would like to return an array instead of returning only string.

PHP code:

return (new Datatables())
    ->query($query)
    ->edit('raw_name', function ($col) {
        $picture = (new Picture())
            ->setModuleType($col['module_type'])
            ->setRawName($col['raw_name'])
            ->setExtension($col['extension'])
            ->setConverted($col['converted'])
            ->setCreatedAt($col['created_at']);

        return [
            'large' => $picture->getUrl(),
            'small' => $picture->getUrl('small'),
        ];
    })
    ->generate()
    ->toJson();

JS code:

...
{
    data: "raw_name",
    className: "text-center",
    defaultContent: "",
    orderable: false,
    searchable: false,
    render: (value, type, row) => {
        return `<a class="item" href="${value['large']}">
          <img src="${value['small']}" alt="${row['title']}" height="48" class="border">
        </a>`
    },
},
...

I suggest to remove a string return type from Ozdemir\Datatables\Column->value() method or change it to mixed.

Thanks in advance.