yii2 GridView 下拉搜索实现案例教程
下拉搜索,我们先来看看预期的效果图
具体怎么实现喃?考虑到一张数据表要下拉效果的字段可能有很多个,我们先在其model中实现一个方法方便后续操作
/** * 下拉筛选 * @column string 字段 * @value mix 字段对应的值,不指定则返回字段数组 * @return mix 返回某个值或者数组 */ public static function dropDown ($column, $value = null) { $dropDownList = [ "is_delete"=> [ "0"=>"显示", "1"=>"删除", ], "is_hot"=> [ "0"=>"否", "1"=>"是", ], //有新的字段要实现下拉规则,可像上面这样进行添加 // ...... ]; //根据具体值显示对应的值 if ($value !== null) return array_key_exists($column, $dropDownList) ? $dropDownList[$column][$value] : false; //返回关联数组,用户下拉的filter实现 else return array_key_exists($column, $dropDownList) ? $dropDownList[$column] : false; }
<?= GridView::widget([ "dataProvider" => $dataProvider, "columns" => [ // ...... [ "attribute" => "is_hot", "value" => function ($model) { return Article::dropDown("is_hot", $model->is_hot); }, "filter" => Article::dropDown("is_hot"), ], [ "attribute" => "is_delete", "value" => function ($model) { return Article::dropDown("is_delete", $model->is_delete); }, "filter" => Article::dropDown("is_delete"), ], // ...... ], ]); ?>
像这样,我们就简单地实现了两个下拉效果,要实现筛选功能,在你的dataProvider自定添加该字段的搜索条件即可
推荐阅读