首页 > 解决方案 > 如何将参数从控制器传递到视图内的另一个视图(表单)

问题描述

这是我的控制器中的 actionIndex()。

 public function actionIndex()
    {
     $featured= new ActiveDataProvider([
        'query'=>News::find()
        ->where(['not', ['featuredOrder' => null]])
        ->orderBy('featuredOrder'),
        ]);

     $checkList=Featured::find()
        ->joinWith('news')
        ->where(['news.featuredOrder'=>null])
        ->orderBy('featuredOrder')
        ->all();

        return $this->render('index', [
            'dataProvider' => $featured,
            'checkList'=>$checkList,
        ]);

我的视图中有一个index由该控制器呈现的列表视图。如果单击列表视图的一个项目,它将显示每个项目的详细信息视图,以及update更新项目数据的按钮,该按钮将生成一个要更新的表单。我需要将 $checklist 传递给此表单。稍后我将使用这个 $checklist 来填充下拉列表。我想知道如何传递参数。我可以将这部分移到表单视图中,但我认为将它放在视图中并不是一个好习惯。

     $checkList=Featured::find()
        ->joinWith('news')
        ->where(['news.featuredOrder'=>null])
        ->orderBy('featuredOrder')
        ->all();

这是我的索引:

<?php echo \yii\widgets\ListView::widget([
       'dataProvider' => $featured,
       'itemView'=>'_post',
       'options'=>['class'=>'row'], 
       'itemOptions'=>['class'=>'col-md-4'], 
       'summary'=>'', 
       'viewParams'=>['cekList'=>'cekList'],
        'pager' => [
        'options'=>['class'=>'pagination justify-content-center'],
        'linkContainerOptions'=>['class'=>'page-item'],
        'linkOptions'=>['class'=>'page-link'],

_post 视图

div class = "panel panel-default">

            <div class = "panel-body">
                <h2 class="truncate text-center"><?=Html::a($model->title, ['view', 'id' => $model->id] ) ?>    </h2>
                <hr>
             </div>
 <!-- another block of code, but unrelated, so I won't include it -->

这是 view.php 文件,如果_post单击上面的项目标题,则会呈现该文件。

 <div class="row justify-content-between">
        <div class="col-xs-6">
            <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
            <?= Html::a('Delete', ['delete', 'id' => $model->id], [
                'class' => 'btn btn-danger',
                'data' => [
                    'confirm' => 'Do you want to delete this post?',
                    'method' => 'post',
                ],
            ]) ?>

如果单击更新按钮,它将呈现一个表单。我想将参数传递给这个表单。

标签: yii2

解决方案


我的答案基于此查询:

$checkList=Featured::find()
        ->joinWith('news')
        ->where(['news.featuredOrder'=>null])
        ->orderBy('featuredOrder')
        ->all();

如果您只想使用上面的查询进行下拉,有两种方法可以做到这一点:

1. 在控制器中创建一个方法并使用数组辅助方法为下拉列表在查询中添加选择语句

 public function checklistDropdown(){
       $items = Featured::find()
            ->joinWith('news')
            ->where(['news.featuredOrder'=>null])
            ->orderBy('featuredOrder')
            ->all();
      $items = ArrayHelper::map($items, 'id', 'name');
   }

在您的索引操作中调用此方法传递就像您传递模型和数据提供者一样

2.我认为第二种选择更可行

为通用下拉列表创建一个组件助手,在该组件中添加上述方法并使用该组件调用您视图中的方法,您可以将该方法定义为STATIC。它将是可重复使用的。


推荐阅读