1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| class sfValidatorDoctrineCode extends sfValidatorSchema
{
/**
* Constructor.
*
* @param array An array of options
* @param array An array of error messages
*
* @see sfValidatorSchema
*/
public function __construct($options = array(), $messages = array())
{
parent::__construct(null, $options, $messages);
}
/**
* Configures the current validator.
*
* Available options:
*
* * model: The model class (required)
* * column: The unique column name in Doctrine field name format (required)
* If the uniquess is for several columns, you can pass an array of field names
* * primary_key: The primary key column name in Doctrine field name format (optional, will be introspected if not provided)
* You can also pass an array if the table has several primary keys
* * connection: The Doctrine connection to use (null by default)
* * throw_global_error: Whether to throw a global error (false by default) or an error tied to the first field related to the column option array
*
* @see sfValidatorBase
*/
protected function configure($options = array(), $messages = array())
{
$this->addRequiredOption('model');
$this->addRequiredOption('column');
$this->addOption('primary_key', null);
$this->addOption('connection', null);
$this->addOption('throw_global_error', false);
$this->setMessage('invalid', 'An object with the same "%column%" already exist.');
}
/**
* @see sfValidatorBase
*/
protected function doClean($values)
{
$originalValues = $values;
$table = Doctrine_Core::getTable($this->getOption('model'));
if (!is_array($this->getOption('column')))
{
$this->setOption('column', array($this->getOption('column')));
}
//if $values isn't an array, make it one
if (!is_array($values))
{
//use first column for key
$columns = $this->getOption('column');
$values = array($columns[0] => $values);
}
$q = Doctrine_Core::getTable($this->getOption('model'))->createQuery('a');
foreach ($this->getOption('column') as $column)
{
$colName = $table->getColumnName($column);
if (!array_key_exists($column, $values))
{
// one of the column has be removed from the form
return $originalValues;
}
$q->addWhere('a.' . $colName . ' = ?', $values[$column]);
}
$object = $q->fetchOne();
// if no object or if we're updating the object, it's ok
if ($object )
{
return $originalValues;
}
$error = new sfValidatorError($this, 'invalid', array('column' => implode(', ', $this->getOption('column'))));
if ($this->getOption('throw_global_error'))
{
throw $error;
}
$columns = $this->getOption('column');
throw new sfValidatorErrorSchema($this, array($columns[0] => $error));
}
} |
Partager