CDefaultValueValidator.php 1.4 KB

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