kartik-v / yii2-date-range

A Date Range Picker for Bootstrap useful for reports and filtering.
http://demos.krajee.com/date-range
Other
93 stars 81 forks source link

Add Date Range Behavior #90

Closed daixianceng closed 7 years ago

daixianceng commented 7 years ago

DateRangeBehavior automatically fills the specified attributes with the parsed date range values.

For example:

use kartik\daterange\DateRangeBehavior;

class UserSearch extends User
{
    public $createTimeRange;
    public $createTimeStart;
    public $createTimeEnd;

    public function behaviors()
    {
        return [
            [
                'class' => DateRangeBehavior::className(),
                'attribute' => 'createTimeRange',
                'dateStartAttribute' => 'createTimeStart',
                'dateEndAttribute' => 'createTimeEnd',
            ]
        ];
    }

    public function rules()
    {
        return [
            // ...
            [['createTimeRange'], 'match', 'pattern' => '/^.+\s\-\s.+$/'],
        ];
    }

    public function search($params)
    {
        $query = User::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $this->load($params);
        if (!$this->validate()) {
            $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere(['>=', 'createdAt', $this->createTimeStart])
              ->andFilterWhere(['<', 'updatedAt', $this->createTimeEnd]);

        return $dataProvider;
    }
}