2010-08-31 64 views
4

我試圖創建一個表單,基於HTML表單字段中的選擇選項來更改字段的驗證。例如:如果用戶從下拉字段「選項」中選擇選項1,我希望字段「度量」驗證爲sfValidatorInteger。如果用戶從字段「選項」中選擇選項2,我希望字段「公制」驗證爲sfValidatorEmail等。Symonfy 1.4動態驗證可能嗎?

所以在公共函數configure(){我有switch語句來捕獲「options 「,並根據從」選項「返回的值創建驗證器。

1.)如何獲取「選項」的值?我已經試過:

$this->getObject()->options 
$this->getTaintedValues() 

,因此目前工作對我來說唯一的一點是,但它不是真正的MVC:

$params = sfcontext::getInstance()->getRequest()->getParameter('options'); 

2)當我已經捕捉到了這個信息,我該怎麼分配「度量」的值到不同的字段? (「度量」在db中不是真正的列)。所以我需要將「度量」的值分配給不同的領域,如「電子郵件」,「年齡」......目前我在後驗證器這樣處理這個問題,只是想知道我是否可以在配置中分配值):

$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkMetric')))); 

public function checkMetric($validator, $values) { 

} 

謝謝!

回答

6

你想使用一個驗證器。嘗試在你的形式做這樣的事情:

public function configure() 
{ 
    $choices = array('email', 'integer'); 
    $this->setWidget('option', new sfWidgetFormChoice(array('choices' => $choices))); //option determines how field "dynamic_validation" is validated 
    $this->setValidator('option', new sfValidatorChoice(array('choices' => array_keys($choices))); 
    $this->setValidator('dynamic_validation', new sfValidatorPass()); //we're doing validation in the post validator 
    $this->mergePostValidator(new sfValidatorCallback(array(
    'callback' => array($this, 'postValidatorCallback') 
))); 
} 

public function postValidatorCallback($validator, $values, $arguments) 
{ 
    if ($values['option'] == 'email') 
    { 
    $validator = new sfValidatorEmail(); 
    } 
    else //we know it's one of email or integer at this point because it was already validated 
    { 
    $validator = new sfValidatorInteger(); 
    } 
    $values['dynamic_validation'] = $validator->clean($values['dynamic_validation']); //clean will throw exception if not valid 
    return $values; 
} 
+0

謝謝你的幫助!我以這種方式工作。我不知道mergePostValidator和$ validator-> clean()。 您是否知道將字段名稱附加到$ validator-> clean()?引發的錯誤消息的方法。在這種情況下,它將是'選項'字段。 – 2010-08-31 23:08:17

0

1)在發佈驗證器中,值可以通過using the $values parameter訪問。只需使用$ values ['options']並且它應該沒問題...或者您想從另一部分代碼中訪問這些值嗎? $ this-> getObject() - > widgetSchema ['options']應該可以工作我認爲,一旦你的表單綁定到一個對象。

2)configure()方法在窗體構造函數的末尾被調用,所以值沒有綁定,也沒有訪問權限,除非你用db中的對象初始化表單(不需要任何驗證) 。但是如果你想從$ _POST初始化你的表單,那麼一個驗證器肯定會成爲恕我直言。

+0

謝謝你的回答。這真的很有用,我決定將我的代碼移動到後驗證器並按照您的建議捕獲$值。謝謝。 – 2010-08-31 23:09:16

0

我得到了驗證錯誤拋出一個sfValidatorErrorSchema代替sfValidatorError的一起顯示的領域。

$values['dynamic_validation'] = $validator->clean($values['dynamic_validation']); 

... ...變得

try 
{ 
    $values['dynamic_validation'] = $validator->clean($values['dynamic_validation']); 
} 
catch(sfValidatorError $e) 
{ 
    $this->getErrorSchema()->addError($e, 'dynamic_validation'); 
    throw $this->getErrorSchema(); 
} 

不知道這是爲了得到這樣的結果的最佳方式,但似乎在此刻爲我工作。