Friends, how do I get my DatePicker component below (in Yii2 Framewok), filter a field of type datetime
? Since in the component I can only specify the date
format.
_search.php file:
<?php
echo DatePicker::widget([
'model' => $model,
'attribute' => 'start_date',
'attribute2' => 'end_date',
'language' => 'pt',
'type' => DatePicker::TYPE_RANGE,
'separator' => 'até',
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'autoclose'=>true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd',
]
]);
?>
UPDATE
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'created' => SORT_DESC,
]
],
'pagination' => [
'pageSize' => 100,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created' => $this->created,
'updated' => $this->updated,
'closed' => $this->closed,
'user_id' => $this->user_id,
'status_id' => $this->status_id,
'location_id' => $this->location_id,
'typeperson_id' => $this->typeperson_id,
'field_cpfcnpj' => $this->field_cpfcnpj,
]);
$query->andFilterWhere(['between', 'created', $this->start_date, $this->end_date]);
$query->andFilterWhere(['between', 'closed', $this->start_closed, $this->end_closed]);
return $dataProvider;
}
If i understand correctly, you want to submit form using the date range which should filter the records using the given range.
Looking at you
search()
method it looks like you have declared 2 public properties/fields in the search model with the namestart_date
andend_date
which you are using with theDatePicker
and you are trying to compare the range with the columncreated
.You need to do the following in order to filter the records correctly
Make sure for the following
The
start_date
andend_date
are declared inside thesafe
rules for theReportSearch
model.You need to use the
\yii\db\Expression
to convert the date in the column to the desired format, and use thephp:date
to format the given date ranges i.estart_date
andend_date
.Add the following before you return the
$dataProvider
in thesearch()
methodNote: if you have the
created
column saved astimestamp
then you need to wrap the field name in the existing query withFROM_UNIXTIME
like below, otherwise if the column is ofDATE
orDATETIME
the above will work.Column type is of TIMESTAMP
Your complete
search()
method will look like below