1: <?php
2: /**
3: * CDefaultValueValidator class file.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CDefaultValueValidator sets the attributes with the specified value.
13: * It does not do validation but rather allows setting a default value at the
14: * same time validation is performed. Usually this happens when calling either
15: * <code>$model->validate()</code> or <code>$model->save()</code>.
16: *
17: * @author Qiang Xue <qiang.xue@gmail.com>
18: * @package system.validators
19: */
20: class CDefaultValueValidator extends CValidator
21: {
22: /**
23: * @var mixed the default value to be set to the specified attributes.
24: */
25: public $value;
26: /**
27: * @var boolean whether to set the default value only when the attribute value is null or empty string.
28: * Defaults to true. If false, the attribute will always be assigned with the default value,
29: * even if it is already explicitly assigned a value.
30: */
31: public $setOnEmpty=true;
32:
33: /**
34: * Validates the attribute of the object.
35: * @param CModel $object the object being validated
36: * @param string $attribute the attribute being validated
37: */
38: protected function validateAttribute($object,$attribute)
39: {
40: if(!$this->setOnEmpty)
41: $object->$attribute=$this->value;
42: else
43: {
44: $value=$object->$attribute;
45: if($value===null || $value==='')
46: $object->$attribute=$this->value;
47: }
48: }
49: }
50:
51: