Yii2中如何将GridView的自定义URL值传递至其他模型
在Yii2 GridView中传递自定义URL参数到其他模型的实现方法
嘿,我来帮你搞定这个需求~ 要把GridView里的自定义URL参数传递到其他模型,咱们分两步操作就可以轻松实现:
1. 修改GridView的ActionColumn,生成带自定义参数的URL
你原来的ActionColumn里的create按钮默认是基于主键生成URL的,咱们可以通过urlCreator闭包函数来自定义要传递的参数,把当前行模型的字段值直接拼到目标URL里。修改后的代码如下:
['class' => 'yii\grid\ActionColumn', 'template' => '{create}', // 自定义URL生成逻辑,按需传递参数 'urlCreator' => function ($action, $model, $key, $index) { if ($action === 'create') { // 替换成你实际要跳转的控制器/动作,比如目标模型的create页面路由 return Url::to([ 'target-model/create', // 这里添加需要传递的参数,值取自当前行的模型属性 'department_name' => $model->department_name, 'table_title' => $model->table_title, 'entry_status' => $model->entry_status // 如果需要传递主键(比如你注释掉的company-id),直接加在这里:'company_id' => $model->company_id ]); } // 其他动作按默认逻辑处理即可 return Url::to([$action, 'id' => $key]); }, 'buttons' => [ 'create' => function($url,$model){ return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [ 'title' => Yii::t('yii', 'Entry Data'), ]); } ]],
这里的核心是urlCreator函数,它会为每一行的create按钮生成包含自定义参数的URL,参数值直接对应当前行的模型字段。
2. 在目标模型的控制器动作中接收并使用参数
接下来,在你跳转的目标控制器(比如TargetModelController)的create动作里,获取这些传递过来的参数,然后赋值给模型或者用于业务逻辑:
use Yii; use app\models\TargetModel; public function actionCreate() { $model = new TargetModel(); // 通过GET方式获取从GridView传递来的参数 $departmentName = Yii::$app->request->get('department_name'); $tableTitle = Yii::$app->request->get('table_title'); $entryStatus = Yii::$app->request->get('entry_status'); // 把参数赋值给目标模型的对应属性(根据你的模型字段调整) if (!empty($departmentName)) { $model->department_name = $departmentName; } if (!empty($tableTitle)) { $model->table_title = $tableTitle; } if (!empty($entryStatus)) { $model->entry_status = $entryStatus; } // 常规的表单提交保存逻辑 if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } // 如果需要在视图中直接使用这些参数,也可以一起传递到视图 return $this->render('create', [ 'model' => $model, 'departmentName' => $departmentName, ]); }
这样,当你点击GridView里的create按钮时,就会带着当前行的参数跳转到目标模型的创建页面,参数会自动赋值给模型(也可以在视图里直接调用)。
额外小提示
- 如果参数涉及敏感信息,建议改用POST方式传递,但GridView的ActionColumn默认是GET请求,若参数不敏感,用GET就足够方便。
- 别忘了在目标模型的
rules()方法中允许接收这些参数,否则会被Yii的安全验证拦截。比如在TargetModel里添加:public function rules() { return [ // 其他规则... [['department_name', 'table_title', 'entry_status'], 'safe'], ]; }
内容的提问来源于stack exchange,提问作者lfx
相关产品推荐
相关产品推荐

