How to make a drop down list in yii2?

前端 未结 12 2045
天命终不由人
天命终不由人 2020-12-04 13:07

How to make a dropdown in yii2 using an activeform and a model? Since all the methods has changed in yii2,how it is done

12条回答
  •  天涯浪人
    2020-12-04 13:41

    It Seems there are many good answers for this question .So i will try to give a detailed answer

    active form and hardcoded data

    field($model, 'name')->dropDownList(['1' => 'Yes', '0' => 'No'],['prompt'=>'Select Option']);
    ?>
    

    or

     'Yes', '0' => 'No'];
        echo $form->field($model, 'name')->dropDownList($a,['prompt'=>'Select Option']);
    ?>
    

    active form and data from a db table

    we are going to use ArrayHelper so first add it to the name space by

    
    

    ArrayHelper has many use full functions which could be used to process arrays map () is the one we are going to use here this function help to make a map ( of key-value pairs) from a multidimensional array or an array of objects.

    field($model, 'name')->dropDownList(ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
    ?>
    

    not part of a active form

     'Yes', '0' => 'No']) ;
    ?>
    

    or

     'Yes', '0' => 'No'];
        echo Html::activeDropDownList($model, 'filed_name',$a) ;
    ?>
    

    not an active form but data from a db table

    all(),'id','username'),['prompt'=>'Select User']);
    ?>
    

提交回复
热议问题