how to display default value in dropDownlist

2019-07-27 09:59发布

I have two dropDownlist in index, when I select the submit button it will get action in controller, and it performs some operations and again render the index with gridview, but the Selected dropDownList become blank, how can I set the default in dropDownllist??

Any suggestion should be appreciatable... this is my view

    <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>

this is my controller

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]);

}

when i select dropdown it will gott actionDisplay, and find the dataprovider, and then it again render to index, so that time how can i show default selected value in dropDownlist?

标签: yii2
1条回答
女痞
2楼-- · 2019-07-27 10:11

If you are using an activeRecord then in controllerAction you should assign to the $model->your_fiedl the value you need for default

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

         }

if you don't are using an active record you could use

->dropDownList($yourlist ,$selection) 

eg

 ->dropDownList(ArrayHelper::map(TblPayrollMonth::find()->all() ,3) 
查看更多
登录 后发表回答