How do I properly setup a conditional validator in symfony 1.4?
For some reason, the fields in my form are not being validated. Perhaps someone can point out any errors or missing items in my code. I was trying to follow the example here: http://www.symfony-project.org/cookbook/1_2/en/conditional-validator
Any help is appreciated!
I have the following form class:
<?php
/**
* dnc_btns form.
*
* @package NMPlus
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class dnc_btnsForm extends Basednc_btnsForm
{
public function configure()
{
$this->useFields(array('btn', 'btn_low', 'btn_high', 'company', 'source'));
$this->setValidator('company', new sfValidatorPass());
$this->setValidator('source', new sfValidatorPass());
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'checkBtnType')))
);
}
public function checkBtnType($validator, $values)
{
if (!empty($values['btn']))
{
$this->setValidator('btn', new sfValidatorBtn());
$this->setValidator('btn_low', new sfValidatorPass());
$this->setValidator('btn_high', new sfValidatorPass());
}
if(empty($values['btn']))
{
$this->setValidator('btn_low', new sfValidatorBtn());
$this->setValidator('btn_high', new sfValidatorBtn());
$this->mergePostValidator(
new sfValidatorSchemaCompare('btn_low', sfValidatorSchemaCompare::LESS_THAN, 'btn_high', array(),
array('invalid' => 'The first BTN must be lower than the second.')));
}
return $values;
}
}
And here is my custom validator:
<?php
class sfValidatorBtn extends sfValidatorAnd
{
public function __construct()
{
parent::__construct();
$this->setValidators();
}
public function setValidators()
{
//Btn should be required, not trimmed, and min and max length set.
$this->addValidator(
new sfValidatorString(
array(
'required' => true,
'trim' => false,
'min_length' => 10,
'max_length' => 10,
),
array(
'invalid' => 'BTN must be 10 digits.'
开发者_开发百科 )
)
);
// Adapted from http://stackoverflow.com/questions/1964399/validation-for-a-10-digit-phone-number
$this->addValidator(
new sfValidatorRegex(
array( 'pattern' => '/^([1-9]\d*)/' ),
array( 'invalid' => 'BTN may not start with a 0.')
)
);
//Checking for existance of given btn in database
$this->addValidator(
new sfValidatorDoctrineUnique(
array( 'model' => 'dnc_btns', 'column' => 'btn' ),
array('invalid' => 'This BTN is already in the database.')
)
);
}
}
The checkBtnType() method should perform a validation rather then add new validators.
Your method should return the values if everything is ok and throw an sfValidatorError exception otherwise.
You don't seem to follow the tutorial from the link you pasted.
I didn't tested that (and maybe I'm wrong), bu I think you can perform whole validation in checkBtnType
by just creating validation objects manually:
$validator = new sfValidatorBtn();
$validator->doClean($values['btn']);
Hope that helps.
精彩评论