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.
Author by
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I have the
dropdown
option inYii
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 thedefault selected value for the dropdown options
.So that by default there will beSelect One
when no option is selected.[UPDATE]
It is taking
Select One
as a option when I triedarray('prompt'=>'Choose One')
andarray('empty'=>'Choose One')
also. -
briiC over 11 yearsi'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. Tryprompt
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 over 11 years@NewBie Your model
$students
contains pre-selected value forstudent_name
. You have to reset it before rendering view like for example:$students->student_name = null;
Then adding anempty
option like described in that answer will work for you. -
Admin over 11 years@johnathan so how to make it reset?
-
Stu over 11 yearswould
array_merge(array(''=>'Select One'),CHtml::listData(Students::model()->findAll(), 'student_name', 'student_name'))
work, just prepend the value to the beginning of thelistData()
?