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

datatable: data with function, doesn't work sort #88

Open jlopes90 opened 2 years ago

jlopes90 commented 2 years ago

I use data: function(row) and it works but sorting doesn't work.

Example:

const columns = [];
columns.push({
    data: function(row) {
        return row.id;
    }
});
columns.push({
    data: function(row) {
        return row.name;
    }
});
columns.push({
    data: function(row) {
        const elString = jsoperation.modal(row.json);
        return elString;
    }
});

$(document).ready(function () {
    $('#example').dataTable({
        "serverSide": true,
        "ajax": "example",
        "columns": columns
    });
});
jlopes90 commented 2 years ago

I made the changes more or less and it works fine.


https://github.com/n1crack/datatables/blob/f5b5c327df8525d5ff949c6c90a7752c6071df2b/src/QueryBuilder.php#L88-L99

to

public function setColumnAttributes(): void
{
    $columns = $this->options->columns();
    if ($columns) {
        foreach ($columns as $key => $attr) {
            $index = $attr['data']['_'] ?? $attr['data'];

            if ($index === 'function') {
                $index = $key;
            }

            if ($this->columns->visible()->isExists($index)) {
                $this->columns->visible()->get($index)->attr = $attr;
            }
        }
    }
}

https://github.com/n1crack/datatables/blob/f5b5c327df8525d5ff949c6c90a7752c6071df2b/src/QueryBuilder.php#L277-L305

to

protected function orderBy(): string
{
    ...

    foreach ($orders as $order) {
        $data = $this->options->columns()[$order['column']]['data'];
        $id = $data['sort'] ?? $data['_'] ?? $data;

        if ($id === 'function') {
            $id = $order['column'];
        }

        if ($this->columns->visible()->isExists($id)) {
            $o[] = $this->columns->visible()->get($id)->name.' '.$order['dir'];
        }
    }

    ...
}