How to preload dropdowns in CForm

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

So you want to use CForm (form builder), but need to preload dropdowns in a form? It's simpler than it seems.
You got your CFormModel, CForm and the actual Form, right?
Let's say you have the typical State -> City dependent dropdowns, so you would want to load the from with the State and City selected.

For this example to work, you need a table for countries, states and cities and the must be related (have foreign keys). Or whatever.

In your controller, you create a new form:

$address_model = new AddressFormModel;

And then, if you have a value you do this (in your controller):

$address_model->state_id = $previously_loaded_customer_address_for_example->state_id;
/* same for the city */
$address_model->city_id = $previously_loaded_customer_address_for_example->city_id;

Now, all you have to do, is this in your CForm:

<?php
return array(
	'activeForm'=>array(
		'class'=>'CActiveForm',
		'id'=>'someId',
	),
	'action'=>'someAction',
	'elements'=>array(
		'state_id'=>array(
			'type'=>'dropdownlist',
			/* 
				I already have the country_id in a param variable, so I use it to select states from that country 
				getStates is my method to get States from the DB that belong to country_id
			*/
			'items'=>CHtml::listData(State::model()->getStates(Yii::app()->params['country_id']), 'state_id', 'state'),
			'prompt'=>'Choose...',
		),
		'city_id'=>array(
			'type'=>'dropdownlist',
			/* getCities is my method to get Cities that belong to the State of the address */
			'items'=>CHtml::listData(City::model()->getCities($this->model->state_id), 'city_id', 'city'),
			'prompt'=>'Please choose state',
		),
		/* other elements */
?>

Not only the City dropdown will be filled with Cities from the State, but the chosen City will be preselected in the dropdown. That's pretty cool.

In short, you can access the values of the model in the CForm with

$this->model->your_model_property

API documentation: [CForm]
More info, check the comments too:
http://www.yiiframework.com/doc/guide/1.1/en/form.builder