Main trouble with actionAdmin to set initial filter is to pass to view an CActiveDataProvider, instead the Model.
Passing an CActiveDataProvider you can control conditions to apply to data more carefully, instead using directly search() method of model.
So, if your model for instance has 2 attributes, ‘id’ and ‘date’, I create in model a method searchCriteria() that returns an CDbCriteria object and change search() in this way:
public function searchCriteria()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('date',$this->dataore,true);
return $criteria;
}
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=$this->searchCriteria();
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
So, in controller in actionAdmin you can can write:
public function actionAdmin()
{
$model=new Cashbook('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Cashbook']))
$model->attributes=$_GET['Cashbook'];
$criteria = $model->searchCriteria();
// add initial filter
if($model->date == null) $criteria->addCondition('MONTH(date) = '.date('m'));
$dataProvider = new CActiveDataProvider($model, array('criteria' => $criteria));
// pass to view also CActiveDataProvider
$this->render('admin',array(
'model'=>$model,
'dataProvider' => $dataProvider
));
}
Remember to set ‘dataProvider’ attribute of CGridView to $dataProvider instead $model->search().
I think the problem may be another. I watched the filter that the DATE field does not accept the value 2015-01 (to display only the current month and year), I have to put in the full format, for example 01.17.2015
(In Yii 1 I could search only typing for example 2015 to display all the records of 2015).
In Yii 1, I typed 2014 on DATE field, and the GRIDVIEW showed all the records that had 2014-xx-xx in the DATE field. Similarly to show the records of the current month for example, was so enter 2015-01 (no day).
In Yii 2, it does not. I have to enter a complete date (Example: 10.12.2014).
public function actionIndex()
{
$searchModel = new CashbookSearch();
$searchModel->start_date = date('Y-m-01'); // get start date
$searchModel->end_date = date("Y-m-t");; // get end date
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}