DefaultValueValidator.php 1.52 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
w  
Qiang Xue committed
3
 * DefaultValueValidator class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
10 11
namespace yii\validators;

w  
Qiang Xue committed
12
/**
w  
Qiang Xue committed
13 14 15 16 17 18 19
 * DefaultValueValidator sets the attribute to be the specified default value.
 *
 * By default, when the attribute being validated is [[isEmpty|empty]], the validator
 * will assign a default [[value]] to it. However, if [[setOnEmpty]] is false, the validator
 * will always assign the default [[value]] to the attribute, no matter it is empty or not.
 *
 * DefaultValueValidator is not really a validator. It is provided mainly to allow
w  
Qiang Xue committed
20 21 22
 * specifying attribute default values in a dynamic way.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
23
 * @since 2.0
w  
Qiang Xue committed
24
 */
w  
Qiang Xue committed
25
class DefaultValueValidator extends Validator
w  
Qiang Xue committed
26 27 28 29 30 31
{
	/**
	 * @var mixed the default value to be set to the specified attributes.
	 */
	public $value;
	/**
w  
Qiang Xue committed
32 33 34
	 * @var boolean whether to set the default [[value]] only when the attribute is [[isEmpty|empty]].
	 * Defaults to true. If false, the attribute will always be assigned with the default [[value]],
	 * no matter it is empty or not.
w  
Qiang Xue committed
35 36 37 38 39
	 */
	public $setOnEmpty = true;

	/**
	 * Validates the attribute of the object.
w  
Qiang Xue committed
40
	 * @param \yii\base\Model $object the object being validated
w  
Qiang Xue committed
41 42
	 * @param string $attribute the attribute being validated
	 */
w  
Qiang Xue committed
43
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
44
	{
w  
Qiang Xue committed
45
		if (!$this->setOnEmpty || $this->isEmpty($object->$attribute)) {
w  
Qiang Xue committed
46 47 48 49 50
			$object->$attribute = $this->value;
		}
	}
}