何らかの理由で、私のフォームのフィールドが検証されていません。おそらく誰かが私のコード内のエラーや欠落している項目を指摘することができます。私はここの例に従おうとしていた:http://www.symfony-project.org/cookbook/1_2/en/conditional-validatorsymfony 1.4で条件バリデータを正しく設定するにはどうしたらいいですか?
何か助けていただきありがとうございます!
私は、次のフォームクラスを持っている:
<?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;
}
}
そして、ここでは私のカスタムバリデータである:
<?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.')
)
);
}
}
私はこのチュートリアルを出発点として使用しました。私は自分の目的に合うようにそれから逸脱しました。 checkBtnType()メソッドで検証を実行する必要がある場合は、コードのその部分をカスタムバリデータに含める方が良いでしょうか?また、既存のバリデータを実装する方法があるので、私はそれらを書き直す必要はありませんか?フィードバックをお寄せいただきありがとうございます。 –
もちろん、カスタムバリデーターを実装する方が良いでしょう。何があなたを止める?既存のバリデータを拡張して再利用することができます(別のバリデータクラスを拡張するクラスを作成する)。 –