H
H
hollanditkzn2018-02-20 10:07:12
Yii
hollanditkzn, 2018-02-20 10:07:12

How can I search grid records by date in dd.mm.yyyy format?

I use 2 widgets

"kartik-v/yii2-widgets": "^3.4",
        "kartik-v/yii2-field-range": "^1.3"

But in this date format yyyy-mm-dd, it normally displays records from the search, in this format dd.mm.yyyy nothing happens at all. It is indicated in ajax that 200 is the code and there are no errors.
My implementation in UserSearch
<?php
....
class UserSearch extends User
{
    public $nameEmployee;
    public $date_from;
    public $date_to;
  
    public function rules()
    {
        return [
            ...
            [['date_from', 'date_to'], 'date', 'format' => 'php:Y-m-d']
        ];
    }
    public function scenarios()
    {
        return Model::scenarios();
    }
    public function search($params)
    {
        $query = User::find()->where(['active' => User::WORK]);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
...

        $query->andFilterWhere(['like', 'username', $this->username])
            ...
/** Вот тут должно конвертировать в любом случае что пришло в таком формате 2017-09-10 что пришло в таком формате 10.09.2017, верно же? она все равно будет в unix формате */
            ->andFilterWhere(['>=', 'created_at', $this->date_from ? strtotime($this->date_from.' 00:00:00') : null])
            ->andFilterWhere(['<=', 'created_at', $this->date_to ? strtotime($this->date_to.' 23:59:59') : null]);

        return $dataProvider;
    }
}

And in gridview
[
                    'filter' => DatePicker::widget([
                        'model' => $searchModel,
                        'attribute' => 'date_from',
                        'attribute2' => 'date_to',
                        'type' => DatePicker::TYPE_RANGE,
                        'separator' => '-',
                        'pluginOptions' => ['format' => 'dd.mm.yyyy'],
                    ]),
                    'attribute' => 'created_at',
                    'format' => 'datetime',
                    'label' => 'Дата приема'
                ],

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Artem, 2018-02-20
@hollanditkzn

Do you have MySQL?
If so, then mysql only accepts the date type in Ymd format. I solve the problem at the level of the search model as follows:

$query->andFilterWhere([
            'birth_date' => $this->birth_date ? \Yii::$app->formatter->asDate($this->birth_date, 'php:Y-m-d') : null,
        ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question