Yii 2.0: Yii2 default values for Index data Provider



maybe a lot of you will not find this interesting but, for me has been really helpful.

I have a list of quotations ( yes, my application manage quotations) in the default index of my controller, and I created different indexes depending on the status of these quotations ( DRAFT, CANCELED, COMPLETED, CREATED ), and what I did next was merge the request array with the default information of the index file.

public function actionIndexdraft() {
        $searchModel = new CotizacionSearch;
        $queryParams = array_merge(array(),Yii::$app->request->getQueryParams());
        $queryParams["CotizacionSearch"]["idEjecutivo"] = 1 ;
        $queryParams["CotizacionSearch"]["status"] = "DRAFT" ;
        $dataProvider = $searchModel->search($queryParams);
        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'searchModel' => $searchModel,

I the last example, I am creating by default the values for "status" and "idEjecutivo" and it does not matter what you write on the search field, they are going to be always including these information.

I hope that someone finds it useful, I did.

Total 3 comments

#19974 report it
amirajlo at 2016/11/06 09:51am

whene use abow code , you should first of all set your attributed in modelSearch :

            'id' => $this->id,
            'is_deleted' => $this->is_deleted,
            'user_id' => $this->user_id,
            'parent_id' => $this->parent_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        $query->andFilterWhere(['like', 'title', $this->title])
                ->andFilterWhere(['like', 'content', $this->content]);
        return $dataProvider;
#19561 report it
kory at 2015/09/08 03:35pm
Sintax Error

You should add [ ] to use Misbahul D Munir example.

$searchModel = new CotizacionSearch(
              [ 'idEjecutivo' => 1,
               'status' => 'DRAFT', ]
#17369 report it
Misbahul D Munir at 2014/05/29 10:30am

How about this

public function actionIndexdraft() {
        $searchModel = new CotizacionSearch(
               'idEjecutivo' => 1,
               'status' => 'DRAFT',
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'searchModel' => $searchModel,

can it work?

Leave a comment

Please to leave your comment.

Write new article