Chumper / Datatable

This is a laravel 4 package for the server and client side of datatables at http://datatables.net/
https://github.com/Chumper/Datatable
388 stars 154 forks source link

Sorting by date not working #296

Open PhiloNL opened 9 years ago

PhiloNL commented 9 years ago

Hi there!

I have a date column, but sorting doesn't seem to be working properly.

screen shot 2015-04-20 at 10 32 09

screen shot 2015-04-20 at 10 31 58

        $dateColumn = new DateColumn('created_at', DateColumn::CUSTOM, 'd-m-Y');

        return Datatable::collection($posts)
            ->showColumns('title', 'author', 'date')
            ->addColumn('title', function ($model)
            {
                return $model->present()->adminLink;
            })
            ->addColumn($dateColumn)
            ->addColumn('author', function ($model)
            {
                if ($user = $model->user)
                {
                    return $user->getFullName();
                }
            })
            ->setAliasMapping(true)
            ->make();
Datatable::table()
            ->addColumn(array('title' => trans('core::posttypes.title'), 'author' => trans('core::posttypes.author'), 'created_at' => trans('core::posttypes.date')))
            ->setUrl(route('admin.post-types.datatable', $this->getType()))
            ->render();

Is this a bug or am I doing something wrong?

Thanks!

davepgreene commented 9 years ago

Looks like a bug. Seems like the sorting is done after the ->format() call is done and is just doing string sorting without any kind of comparison method.

davepgreene commented 9 years ago

My interim solution is to output all dates as ISO-8601 strings (which are nicely string sortable) and then doing something like this:

$table->setCallbacks('rowCallback', "function(row, data, index) {
    _.forEach(data, function(value, index) {
        var dt = moment(value, moment.ISO_8601);
        if(dt.isValid()) {
            $('td:eq(' + index + ')', row).text(dt.format('MM/DD/YYYY'));
        }
    });
}");
timgws commented 9 years ago

The sorting from a database point of view is not correct (db dates will be sorted yyyy-mm-dd).

It would be interesting to see what the SQL statement was for this sorting, because the dates should be sorted correctly.

davepgreene commented 9 years ago

@timgws see my comment about how sorting is being done after the column is being formatted. See CollectionEngine::getArray(), specifically the call to compileArray() before doInternalOrder().

compileArray() renders the column which, in the case of a DateColumn formats the DateTime object.