如何在dropDownlist中显示默认值

时间:2017-06-19 08:30:42

标签: yii2

我在索引中有两个dropDownlist,当我选择提交按钮时它将在控制器中获取动作,并执行一些操作并再次使用gridview呈现索引,但是选定的dropDownList变为空白,我该如何设置默认值dropDownllist ??

任何建议都应该值得赞赏...... 这是我的观点

    <div class="col-sm-12" align="center">
                <?= $form->field($model, 'fk_int_payroll_month')->dropDownList(
                    ArrayHelper::map(TblPayrollMonth::find()->all(), 'pk_int_payroll_month_id','vchr_month'),
                ['prompt'=> 'Select...'])
                ?> 
</div>


<div class="col-sm-12" align="center">
            <?= $form->field($model, 'fk_int_payroll_year')->dropDownList(
                ArrayHelper::map(TblPayrollYear::find()->all(), 'pk_int_payroll_year_id','year'),
                ['options' => [isset($_POST['fk_int_payroll_year'])?'fk_int_payroll_year':'' => ['Selected'=>true]]],
            ['prompt'=> 'Seect...'])
            ?>
        </div>

这是我的控制器

public function actionDisplay()
    {
        $model      =   new TblPayroll();
        if(Yii::$app->request->post()!=null) 
        {
            $data = Yii::$app->request->post();
            // var_dump($data);
            // die;
            $month = $data['TblPayroll']['fk_int_payroll_month'];
            $year = $data['TblPayroll']['fk_int_payroll_year'];

            /* Be careful with this! */
            $dataProviderSearch = new ActiveDataProvider
            ([
                'query' => TblPayroll::find()->where(['fk_int_payroll_month'=>$month, 'fk_int_payroll_year'=> $year]),
                'pagination' => ['pageSize' => 5],
            ]);


            if($dataProviderSearch)
            {
                return $this->render('index', [
                'dataProviderSearch' => $dataProviderSearch,
                'model' => $model,
                ]);
            }
        }
            else{
                 return $this->render('index', ['model' => $model]);

}

当我选择下拉列表时,它将gott actionDisplay,并找到dataprovider,然后再次渲染到索引,那么我该如何在dropDownlist中显示默认选择值?

1 个答案:

答案 0 :(得分:1)

如果您使用的是activeRecord,那么在controllerAction中,您应该为$ model-&gt; your_fiedl指定默认值所需的值

     else{
             $model->fk_int_payroll_month  = 3
             return $this->render('index', ['model' => $model]);

         }

如果您没有使用活动记录,则可以使用

->dropDownList($yourlist ,$selection) 

例如

 ->dropDownList(ArrayHelper::map(TblPayrollMonth::find()->all() ,3)