I am new in yii. I have city name and value in tbl_city and I want to show city comb box on add user page so that user can choose city and submit. After this i have to save city value in database and on edit user page i have to show city combo and select the city value by default on the basis of city id which is store in table. same i have to show on search section and view section.
CHtml::listData() returns an array of value-label pairs. It serves quite well when used in a CActiveForm::dropDownList to generate a list of options.
And when you use CActiveForm::dropDownList, the initial selection of the dropDownList is automatically set according to your model … It should show ‘Select your city’ when you are creating a new model instance, and should show the name of the selected city when you are updating the existing one.
Well, giix should do some kind of magic and automatically generate a form code that is almost similar to the example above … I’m not very sure because I’m not familiar with it. You may try it, it’s one of the most favored extensions.
But I think it’s not too bad to do it manually, especially when you are not accustomed to the concept of relational active record.
This assumes that your User table has a cityId column to populate from the related table. It should give you a dropdown list that shows the names but will return the id number on submit.
The _search partial uses an ActiveForm also, so _search should be updated the same way.
The _view partial couldn’t be simpler. Just replace the normal
<?php echo CHtml::encode($data->cityId); ?>
with
<?php echo CHtml::encode($data->city->name); ?>
Most place you have a User model loaded, in fact, you should be able to use similar drill-downs, for example, in the view, you can replace $model->cityId with $model->city->name.
GridViews and views in child models are a little more tricky. For example, in the User model, you can also add city name to the GridView in admin with the following steps:
declare a public variable e.g. $city_grid
in the rules array, make sure to include city_grid in your list of items safe on search
in your attribute labels, make sure to assign a label to city_grid, e.g. ‘City’
in your search function, include the following in your criteria:
That should replace the cityId field in your GridView with the name of the city, including the ability to search and sort on the city name instead of the id.
If you have tables with many:many relations, for example an Image table that you would want to link to User and to City, you will also need to set up a city_grid in your CityImage model, and then in the DetailView of the regular view file, replace the cityId in the attributes array with:
I don’t know if that’s the best way to manage pure relational tables in Yii, but it is simple to set up using Gii, and it works with this modification to refer back to the parent table(s).