Xem 'Lưu ý: Ngữ cảnh xác thực' tại số page này. Zend_Form chuyển ngữ cảnh này đến mọi Zend_Form_Element :: isValid gọi làm tham số thứ hai. Vì vậy, chỉ cần viết trình xác thực của riêng bạn để phân tích ngữ cảnh.
EDIT:
Được rồi, tôi nghĩ tôi sẽ tự mình chụp. Nó không được thử nghiệm, cũng không phải là một phương tiện cho tất cả các kết thúc, nhưng nó sẽ cho bạn một ý tưởng cơ bản.
class My_Validator_OneFieldShouldBePresent extend Zend_Validator_Abstract
{
const NOT_PRESENT = 'notPresent';
protected $_messageTemplates = array(
self::NOT_PRESENT => 'Field %field% is not present'
);
protected $_messageVariables = array(
'field' => '_field'
);
protected $_field;
protected $_listOfFields;
public function __construct(array $listOfFields)
{
$this->_listOfFields = $listOfFields;
}
public function isValid($value, $context = null)
{
if(!is_array($context))
{
$this->_error(self::NOT_PRESENT);
return false;
}
foreach($this->_listOfFields as $field)
{
if(isset($context[ $field ]))
{
return true;
}
}
$this->_field = $field;
$this->_error(self::NOT_PRESENT);
return false;
}
}
Cách sử dụng:
$oneOfTheseFieldsShouldBePresent = array('companyname', 'companyother');
$companyname = new Zend_Form_Element_Text('companyname');
$companyname->setLabel('Company Name');
$companyname->setDecorators($decors);
$companyname->addValidator(new My_Validator_OneFieldShouldBePresent($oneOfTheseFieldsShouldBePresent));
$this->addElement($companyname);
$companyother = new Zend_Form_Element_Text('companyother');
$companyother->setLabel('Company Other');
$companyother->setDecorators($decors);
$companyname->addValidator(new My_Validator_OneFieldShouldBePresent($oneOfTheseFieldsShouldBePresent));
$this->addElement($companyother);
Nguồn
2010-03-09 19:14:41