CActiveForm dropdownlist and rules


I try to update a form where I have the following dropdownlist:

<?php echo $form->dropDownList($role,'IDRole',CHtml::listData($role->GetMainRoles(),"IDRole","Ruolo"),array('prompt'=>'Seleziona')); ?>

in the updateAction code I have:


the problem is that the model attributes don’t update with the new value in $_POST[‘Role’] and always show the original values.

Trying to figure out why I go to the model rules and noticed that by default the IDRole attribute is not listed because, i guess, it normally wont receive user inputs.

So I added the IDRole to the rules marking it as required and numeric and all is working right.

the $role->attributes are correctly updated, but I cannot figure out why I need to mark my fields as required to accomplish my task.

You don’t have to have them required, you could mark them as ‘safe’ in the rule instead which would allow them to update if present, but not require that they be filled in.

these are my rules:

public function rules()


	// NOTE: you should only define rules for those attributes that

	// will receive user inputs.

	return array(

		array('Ruolo, IDRole', 'required'),

		array('Tipo, IDRole', 'numerical', 'integerOnly'=&gt;true),

		array('Ruolo', 'length', 'max'=&gt;50),

		// The following rule is used by search().

		// Please remove those attributes that should not be searched.

		array('IDRole, Ruolo, Tipo', 'safe', 'on'=&gt;'search'),



If I leave only the safe attribues uncommented it doesn’t work.

more info about the context:

the form host 2 models User and Role with relations of many to may each others.

the main role is shown as a item in a dropdownlist.


following your suggestion it works.

I added this row in the model:

 array('IDRole, Ruolo, Tipo', 'safe', 'on'=>'update')

and now IDRole is not more required.

I think that the best way to avoid headache is to use the following code in the form:

CHtml::dropDownList('Ruolo', $ruolo, $model->getRoleOptions(), array('prompt'=>'Seleziona'));

instead of:

<?php echo $form->dropDownList($role,'IDRole',$model->getRoleOptions(),array('prompt'=>'Seleziona')); ?>

the only reason I use the $role model is to take advantage of Yii error handling