The default value is Yii dropDownList

I have this code:

echo $form->dropDownList($model, 
                 'defaultPrinterId', 
                  CHtml::listData(Printer::model()->findAll(), 'id', 'name'), 
                  array('prompt' => '-- None--')); 

Which gives me a dropdown like this:

<select id="LabelType_defaultPrinterId" name="LabelType[defaultPrinterId]">
    <option value="">-- None --</option>
</select>

However, when a value is added to my table in form messages, where defaultPrinterId is 0. Instead, how would I make it null, since this is a field with a null value?

+5
source share
2 answers

In your controller, after loading the attributes from, $_POSTdo

$model->defaultPrinterId = $model->defaultPrinterId ? $model->defaultPrinterId : null;

This changes 0to null, otherwise leaves it unchanged.

+6
source

If you want to strictly follow MVC, validation of the values ​​associated with the model must be done, well, the model.

This can be done something like this:

/**
 * @return array validation rules for model attributes.
 */
public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        //rules rules rules...
        array('defaultPrinterId', 'default', 'setOnEmpty' => true, 'value' => NULL),
        //rest of the rules
    );
}
+8
source

All Articles