1
votes

I'm using Zend_Form with a registration page. I have a checkbox, that if checked, will show additional billing fields. In my form instance, I only want those extra fields to be setRequired(true) if that checkbox is checked. Is there a way to do this? The problem now is I have to set all the billing fields as setRequired(false), but if the user checks the checkbox, the logic won't care if the fields are empty because they aren't required.

alt text

3

3 Answers

1
votes

I had same problem, and i ended writing my own validator:

<?
class Mh_Validator_RequiredIfCheckbox extends Zend_Validate_Abstract
{
    const SHOULD_BE_NOT_EMPTY = 'shouldBeNotEmpty';

    private $_field;
//protected $_field;
public function __construct($field)
{
    $this->_field = $field;
}    

    protected $_messageTemplates = array(
    self::SHOULD_BE_NOT_EMPTY =>"This field is required"
    );

    /**
     * Defined by Zend_Validate_Interface
     *
     * @param  string $value
     * @return boolean
     */

    public function isValid($value, $context = null)
    {

        if($context[$this->_field]==0 && $value == null)
        {
            $this->_error(self::SHOULD_BE_NOT_EMPTY);
            return false;
        }
    return true;

    }
}
0
votes

OK, so here is what I ended up doing. I created the billing information as a Zend_Form_SubForm and added it to the main Register form. Then, in my controller, on post, I check to see if the checkbox is checked. If its not, then I remove the subform from the main form and validate the form. If there is an error then I re-add the subform so the fields will show up when the form is re-drawn. Hopefully that will help somebody.

-1
votes

Why not simply check whether a POST has been issued (if that is your form's method) and if so look at value of checkbox and set required to false for all elements (perhaps convenient to keep them in an array) before validating with $form->isValid($formData)?

Example:

if ($this->getRequest()->isPost()) {
    $formData = $this->getRequest()->getPost();
    if ($formData['billing_information_different'] == '1') {
        $billingElement1->setRequired(true);
        $billingElement2->setRequired(true);
    }
}