Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend_Form: Element should only be required if a checkbox is checked

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!

like image 389
janoliver Avatar asked Sep 16 '09 09:09

janoliver


1 Answers

I think that the best, and more correct way to do this is creating a custom validator.

You can do this validator in two different ways, one is using the second parameter passed to the method isValid, $context, that is the current form being validated, or, inject the Checkbox element, that need to be checked for validation to occur, in the constructor. I prefer the last:

<?php
class RequiredIfCheckboxIsChecked extends Zend_Validate_Abstract {

    const REQUIRED = 'required';

    protected $element;

    protected $_messageTemplates = array(
        self::REQUIRED => 'Element required'
    );

    public function __construct( Zend_Form_Element_Checkbox $element )
    {
        $this->element = $element;
    }

    public function isValid( $value )
    {
        $this->_setValue( $value );

        if( $this->element->isChecked() && $value === '' ) {
            $this->_error( self::REQUIRED );
            return false;
        }

        return true;
    }

}

Usage:

class MyForm extends Zend_Form {

    public function init()
    {
        //...

        $checkElement = new Zend_Form_Element_Checkbox( 'checkbox' );
        $checkElement->setRequired();

        $dependentElement = new Zend_Form_Element_Text( 'text' );
        $dependentElement->setAllowEmpty( false )
            ->addValidator( new RequiredIfCheckboxIsChecked( $checkElement ) );

        //...
    }

}

I have not tested the code, but I think it should work.

like image 102
jonathancardoso Avatar answered Sep 23 '22 13:09

jonathancardoso