I would write a custom validator and use the provided $context
variable.
A short example
Controller
class MyController extends Zend_Controller_Action {
public function indexAction() {
$form = new Application_Form_Gender();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
/*...*/
}
}
}
}
Form
class Application_Form_Gender extends Zend_Form {
public function init()
{
$this->addElement('radio', 'radio1', array('multiOptions' => array('m' => 'male', 'w' => 'female')));
$this->getElement('radio1')->isRequired(true);
$this->getElement('radio1')->setAllowEmpty(false);
$this->addElement('text', 'textm', array('label' => 'If you are male enter something here');
$this->getElement('textm')->setAllowEmpty(false)->addValidator(new MyValidator('m'));
$this->addElement('text', 'textf', array('label' => 'If you are female enter something here'));
$this->getElement('textf')->setAllowEmpty(false)->addValidator(new MyValidator('f'));
$this->addElement('submit', 'submit');
}
Validator
class MyValidator extends Zend_Validate_Abstract {
const ERROR = 'error';
protected $_gender;
protected $_messageTemplates = array(
self::ERROR => "Your gender is %gender%, so you have to enter something here",
);
protected $_messageVariables = array('gender' => '_gender');
function __construct($gender) {
$this->_gender = $gender;
}
function isValid( $value, $context = null ) {
if (!isset($context['radio1'])) {
return true;
}
if ($context['radio1'] != $this->_gender) {
return true;
}
if (empty($context[sprintf('text%s', $this->_gender)])) {
$this->_error(self::ERROR);
return false;
}
return true;
}
}
As you can see in this example, all the data provided in $form->isValid()
is made available via the $context
variable and with that you can perform any checks you like.