Datetime Field Type - Filters

Ryan Thompson Addons


Datetime v3.0 just got an update that contains a filter view for tables!

Previously the filter was a fallback text search but now allows you to easily search by date range.

Datetime Field Type Filter

Updating

A composer update is all that is needed to bring in this update assuming you are requiring version 3 in your project's composer.json.

Usage

To add it to your table filters just include it in the $filters array of your table builder:

protected $filters = [
    'publish_at',
];

Field Type Filters

If you are curious how we made it - check this out! All you need to do is create a {YourFieldType}Query class and define the filter method:

<?php namespace Anomaly\DatetimeFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeQuery;
use Anomaly\Streams\Platform\Ui\Table\Component\Filter\Contract\FilterInterface;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class DatetimeFieldTypeQuery
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <[email protected]>
 * @author Ryan Thompson <[email protected]>
 */
class DatetimeFieldTypeQuery extends FieldTypeQuery
{

    /**
     * Filter a query by the value of a
     * field using this field type.
     *
     * @param Builder         $query
     * @param FilterInterface $filter
     */
    public function filter(Builder $query, FilterInterface $filter)
    {
        list($from, $to) = explode(' to ', $filter->getValue());

        $from = Carbon::createFromFormat(config('streams::datetime.date_format'), $from)
            ->setTimezone(config('app.timezone'))
            ->setTime(0, 0, 0)// Start at the beginning of the day.
            ->setTimezone(config('streams::datetime.default_timezone'));

        $to = Carbon::createFromFormat(config('streams::datetime.date_format'), $to)
            ->setTimezone(config('app.timezone'))
            ->setTime(23, 59, 59)// Include up to the end of the day.
            ->setTimezone(config('streams::datetime.default_timezone'));

        $query->whereDate($filter->getField(), '>=', $from->format('Y-m-d H:i:s'));
        $query->whereDate($filter->getField(), '<=', $to->format('Y-m-d H:i:s'));
    }
}

Go forth and filter.

- Ryan


No Comments


Please login to leave a comment.