2009-12-29 87 views
2

如何將多個表單元素合併到一個驗證器中?我有包括地址信息如何將多個元素組合到一個驗證器中?

  • 街道地址
  • 郵政編碼
  • 郵局

如果我添加驗證他們每個人作爲streetValidator,zipCodeValidator,postOfficeValidator我結束了問題:在某處可以有foostreet(驗證可以),10101某處(驗證也可以)以及barOffice在某處(驗證也可以)。但所有的地址信息結合起來,沒有地址「foostreet,10101,barOffice」。

現在您有:

<?php 
$f = new Zend_Form(); 

$street = new Zend_Form_Element_Text('street'); 
$f->addElement($street); 

$zip = new Zend_Form_Element_Text('zip'); 
$f->addElement($zip); 

$office = new Zend_Form_Element_Text('office'); 
$f->addElement($office); 

但它應該是:

$f = new Zend_Form(); 
// All three fields are still seperated 
$address = new My_Address_Fields(); 
$address->addValidator(new addressValidator()); 
$f->addElement($address); 

驗證是一樣的東西

class addressValidator extends Zend_Validator_Abstract 
{ 
    public function isValid() 
    { 
    //$street = ???; 
    //$zip = ???; 
    //$office = ???; 

    // XMLRPC client which does the actual check 
    $v = new checkAddress($street, $zip, $office); 
    return (bool)$v->isValid(); 
    } 
} 
+0

我想這是關於如何創建MyAddressField導致問題的部分。你必須爲你的裝飾器創建一個複合的表單元素。看看[這個](http://weierophinney.net/matthew/archives/212-The-simplest-Zend_Form-decorator.html)[系列](http://weierophinney.net/matthew/archives/213-From- [articles](http://weierophinney.net/matthew/archives/217-Creating-composite-elements.html#extended)[在表單裝飾器上]的[inside-out-How-to-layer-decorators.html) (http://devzone.zend.com/article/3450)。特別是鏈接爲'articles'的文章,應該讓你進入 – Gordon 2009-12-29 10:59:04

回答

1

當驗證一個表單元素,驗證給出所有形式值,在$context參數內河所以,你的驗證器是這個樣子:

public function isValid($value, $context = null) 
    { 
    $street = (isset($context['street']))? $context['street'] : null; 
    $zip = (isset($context['zip']))? $context['zip'] : null; 
    $office = (isset($context['office']))? $context['office'] : null; 

    // XMLRPC client which does the actual check 
    $v = new checkAddress($street, $zip, $office); 
    return (bool)$v->isValid(); 
    } 

然後,驗證添加到您的street元素,說。

缺點:這個驗證器是一個有點獨立,附加到一個特定的元素,但不是真的。

優點:它會工作。

+0

因爲沒有'Zend_Validate_Abstract :: __ construct()'需要注意,所以可以使用該方法進行映射,即'Your_Validate :: __ construct($ mapping = array())'這將會像'$ mapping ['streetElementId'] ='street''這樣的方法'Your_Validate :: isValid()'會知道哪些規則來驗證每個元素。 – chelmertz 2010-01-05 09:17:54

相關問題