A
A
AlexRas2017-10-04 19:44:30
MySQL
AlexRas, 2017-10-04 19:44:30

How to properly set up search in yii2 model?

Hello, tell me how to properly filter data in GridView.
DatePicker this https://github.com/2amigos/yii2-date-picker-widget
In GridView set up everything like this:

[
  'attribute' => 'created_at',
  'format' => 'datetime',
  'value' => 'created_at',
  'filter' => DatePicker::widget([
    'model' => $searchModel,
    'attribute' => 'created_at',
    'language' => 'ru',
    'clientOptions' => [
      'autoclose' => true,
      'format' => 'dd.mm.yyyy'
    ],
  ]),
],

The date indication works, the date goes into the model in the dmY format.
The date in the database is stored in int
. I know what needs to be changed here, but I couldn’t understand how:
$query->andFilterWhere([
  'id' => $this->id,
  'status' => $this->status,
  'created_at' => $this->created_at,
  'updated_at' => $this->updated_at,
]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-10-04
@AlexRas

Good evening.
Try the following way.
In the search model, add properties, validation rules, and conditions to the query

public $date_from;
public $date_to;

[['date_from', 'date_to'], 'date', 'format' => 'php:Y-m-d']

$query->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 ]);

Search goes in an interval between dates.
Change to your needs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question