Default value for dropdown option in Yii

15,305

Solution 1

I think you're using the wrong key for the default selected value.

Try:

// array('prompt'=>'Choose One')
echo $form->dropdownList($students,'student_name', CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'), array('prompt'=>'Choose One')); ?>

Solution 2

Use attribute named empty

echo $form->dropdownList(
    $students,
    'student_name', 
     CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'),   
     array('empty'=>'Choose One') // boom!
);

Solution 3

When ever have needed to do this I simply add to the array generated by listData.

<?php echo $form->dropdownList($students,'student_name', array(''=>'Select One') + CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name')); ?>

Has always worked fine for me.

Share:
15,305
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin 8 months

    I have the dropdown option in Yii like this

    <?php echo $form->dropdownList($students,'student_name', CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'), array('selected'=>'Choose One')); ?>
    

    Which html output is something like this

    <select selected="selected" name="Students[student_name]" id="Students_student_name">
    <option value="Alex">Alex</option>
    <option value="John">John</option>
    <option value="Johny">Johny</option>
    <option value="" selected="selected"></option>
    </select> 
    

    But I want the Select One should be the default selected value for the dropdown options.So that by default there will be Select One when no option is selected.

    [UPDATE]

    It is taking Select One as a option when I tried array('prompt'=>'Choose One') and array('empty'=>'Choose One') also.

  • briiC
    briiC over 10 years
    i'm using empty all the time and its working. Does your code returns any array or its empty list? I'm loking at variable $students and i get confused because it should be single record not multiple as variable says to me. Try prompt as @ben-rowe suggest you. it's also valid attribute and give feedback about that. yiiframework.com/doc/api/1.1/CHtml#activeDropDownList-detail
  • Johnatan
    Johnatan over 10 years
    @NewBie Your model $students contains pre-selected value for student_name. You have to reset it before rendering view like for example: $students->student_name = null; Then adding an empty option like described in that answer will work for you.
  • Admin
    Admin over 10 years
    @johnathan so how to make it reset?
  • Stu
    Stu over 10 years
    would array_merge(array(''=>'Select One'),CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name')) work, just prepend the value to the beginning of the listData()?