views:

602

answers:

3

Hey there,

I've got a Form where the user can check a checkbox "create new address" and can then fill out the fields for this new address in the same form.

Now I want to validate the fields of this new address ONLY if the checkbox has been checked. Otherwise, they should be ignored.

How can I do that using Zend_Form with Zend_Validate?

Thanks!

+1  A: 

I've been wondering how to do that in ZF as well, though never had to implement such form feature.

One idea that comes to mind is to create a custom validator that accepts the checkbox field as a parameter, and run it in a validator chain, as documented. If the checkbox is checked, validator could return failure. Then you can check whether all validations failed and only then treat form as having failed validation.

That level of customization of form validation could be inconvenient, so maybe using form's isValidPartial method would be better.

macbirdie
A: 

I didn't actually run this, but it should work within reason. I've done something similar before that worked, but couldn't remember where the code was.

<?php

class My_Form extends Zend_Form
{
  public function init()
  {
    $checkbox = new Zend_Form_Element_Checkbox("checkbox");
    $checkbox->setValue("checked");

    $textField = new Zend_Form_Element_Text("text");

    $this->addElements(array("checkbox", "text"));

    $checkbox = $this->getElement("checkbox");

    if ($checkbox->isChecked() )
    {
       //get textfield
       $textField = $this->getElement("text");

       //make fields required and add validations to it.
       $textField->setRequired(true);
    }

  }

}
Travis
A: 

Here's what I do if I need to validate multiple elements against each other

$f = new Zend_Form();

if($_POST && $f->isValid($_POST)) {
  if($f->checkbox->isChecked() && strlen($f->getValue('element')) === 0) {
    $f->element->addError('Checkbox checked, but element empty');
    $f->markAsError();
  }

  if(!$f->isErrors()) {
    // process
    ...
    ...
  }
}
michal kralik