3
* CExistValidator class file.
5
* @author Qiang Xue <qiang.xue@gmail.com>
6
* @link http://www.yiiframework.com/
7
* @copyright Copyright © 2008-2011 Yii Software LLC
8
* @license http://www.yiiframework.com/license/
12
* CExistValidator validates that the attribute value exists in a table.
14
* This validator is often used to verify that a foreign key contains a value
15
* that can be found in the foreign table.
17
* @author Qiang Xue <qiang.xue@gmail.com>
18
* @version $Id: CExistValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $
19
* @package system.validators
22
class CExistValidator extends CValidator
25
* @var string the ActiveRecord class name that should be used to
26
* look for the attribute value being validated. Defaults to null,
27
* meaning using the ActiveRecord class of the attribute being validated.
28
* You may use path alias to reference a class name here.
33
* @var string the ActiveRecord class attribute name that should be
34
* used to look for the attribute value being validated. Defaults to null,
35
* meaning using the name of the attribute being validated.
38
public $attributeName;
40
* @var array additional query criteria. This will be combined with the condition
41
* that checks if the attribute value exists in the corresponding table column.
42
* This array will be used to instantiate a {@link CDbCriteria} object.
45
public $criteria=array();
47
* @var boolean whether the attribute value can be null or empty. Defaults to true,
48
* meaning that if the attribute is empty, it is considered valid.
50
public $allowEmpty=true;
53
* Validates the attribute of the object.
54
* If there is any error, the error message is added to the object.
55
* @param CModel $object the object being validated
56
* @param string $attribute the attribute being validated
58
protected function validateAttribute($object,$attribute)
60
$value=$object->$attribute;
61
if($this->allowEmpty && $this->isEmpty($value))
64
$className=$this->className===null?get_class($object):Yii::import($this->className);
65
$attributeName=$this->attributeName===null?$attribute:$this->attributeName;
66
$finder=CActiveRecord::model($className);
67
$table=$finder->getTableSchema();
68
if(($column=$table->getColumn($attributeName))===null)
69
throw new CException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
70
array('{column}'=>$attributeName,'{table}'=>$table->name)));
72
$criteria=array('condition'=>$column->rawName.'=:vp','params'=>array(':vp'=>$value));
73
if($this->criteria!==array())
75
$criteria=new CDbCriteria($criteria);
76
$criteria->mergeWith($this->criteria);
79
if(!$finder->exists($criteria))
81
$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} "{value}" is invalid.');
82
$this->addError($object,$attribute,$message,array('{value}'=>$value));