YII2,gradview使用实例

1.view模版中使用

  GridView::widget([

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],



            'id',

            ['attribute'=>'title','headerOptions' => ['width' => '250'],],

            'url:url',

            

            [

                'attribute'=>'type',

                'value' => function ($data) {

                    return '';

                },

                'filter' => '',//是否添加过滤器(本字段的搜索框)

            ],

            [

                'attribute'=>'status',

                'value' => function ($data) {

                    return $data->status?'正常':'不正常';

                },

                'filter' => '',

            ],

            [

               'attribute'=>'created',

                   'value'=>function(){

                        return Yii::$app->user->identity->username;

                    },

                    'filter'=>'',

            ],

             'ctime':datetime',



            ['class' => 'yii\grid\ActionColumn','header' => '操作','template'=>'{update} {delete}'],

        ],

    ]);

2.controller中

        $searchModel = new PostSearch;

        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        return $this->render('index', [

            'dataProvider' => $dataProvider,

            'searchModel' => $searchModel,

        ]);

3.model中

    public function search($params)

    {

        $query = Post::find();

        //$query->joinWith(['user']); // 添加关联条件

        $dataProvider = new ActiveDataProvider([

            'query' => $query,

            'sort'=>['defaultOrder'=>['ctime' => SORT_DESC]]

        ]);

        if (!($this->load($params) && $this->validate())) {

            return $dataProvider;

        }



        $query->andFilterWhere([

            'id' => $this->id,

            [...]

        ]);



        $query->andFilterWhere(['like', 'title', $this->title])->[...];



        return $dataProvider;

    }

 

你可能感兴趣的:(view)