Here we will be looking at how to add dynamic data (entries fro ma database table) to a drop down list using Yii?s Chtml listData. Let?s imagine that we have
a database table called countries and we want to add a drop down list menu to our view which displays the country name and passes the id which in normal html would look like:
1 |
<option value="1">Bangladesh</option> |
Let?s pretend that we have modeled our country table and it is populated with id and name like:
1 ? Bangladesh
2 ? India
3 ? Pakistan
4 ? Srilanka
etc?
Now, lets pretend we have created a form using the ‘Gii tool’ where users car register and one of the fields they need to enter is the country they are from.
We want to display our field as a drop down list. Typically we would have something like this:
1 |
<?php echo $form->textField($model,'country'); ?> |
That creates a text field for our model for the field country. We now want to change this to a drop down list. Really simple!
1 |
<?php echo $form->;dropDownList($model,'country', CHtml::listData(Country::model()->findAll(), 'id', 'name')); ?> |
There we have it, the list is now populated with our entries from our country table using Yii?s CHtml::listData. You see we select the data in the normal way:
1 |
<?php Country::model()->findAll()?> |
This uses our Country model and find all the records. The CHtml::listData needs two other fields, the value and the display value. We have entered the id as the value (the value that gets passed with the form) and the name as the display value (what the user sees). We can get extra fancy by setting what the empty value is by doing:
1 |
<?php echo CHtml::activeDropDownList($model, 'country', CHtml::listData(country::model()->findAll(), 'id', 'title'), array('empty' => '--please select--')); ?> |
Now, when the form is loaded the initial value is our blank ??please select??. Easy stuff, hope that helps.