Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii dropDownList default value

Tags:

php

yii

I have this code:

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

Which gives me a dropdown list like this:

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

However, when the form posts, it adds a value to my table where the defaultPrinterId is 0. Instead of that, how would I make it null, since it's a nullable field?

like image 806
John Zumbrum Avatar asked Jun 05 '12 14:06

John Zumbrum


1 Answers

If you want to follow strictly the MVC, validation of values related to the model should be done in, well, the model.

It can be done with 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
    );
}
like image 58
macinville Avatar answered Sep 24 '22 23:09

macinville