机缘巧合,再次接触到Yii2框架的项目,做了简单的增删查改。涉及到列表项下拉筛选框,自定义表格显示内容。

以下内容仅摘抄了代码最核心的部分,仅供参考

  • 模型
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    class AdvertRecordSearch extends AdvertRecord
    {
        public $start_date;
    
        public $end_date;
    
        public $platforms = [
            'tencent' => '腾讯',
            'alibaba' => '阿里',
        ];
    
        public function rules()
        {
            return [
                [['start_date', 'end_date'], 'safe'],
                ['platform', 'in', 'range' => array_keys($this->platforms)],
            ];
        }
    }
    
  • 控制器
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    class AdvertRecordController extends Controller
    {
        public function actionIndex()
        {
            $searchModel = new AdvertRecordSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider
            ]);
        }
    }
    
  • 视图
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    <?= \yii\grid\GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'date',
            [
                'attribute' => 'platform',
                'filter' => Html::dropDownList('platform', $searchModel->platform, $searchModel->platforms, ['class' => 'form-control', 'prompt' => '全部']),
                'value' => function ($model) {
                    return ArrayHelper::getValue($model->platforms, $model->platform);
                }
            ],
            'total',
        ]
    ])?>