Nov
16th
09

Requiring a checkbox to be ticked in ZendFramework

Zend Framework “documentation” dosn’t say much about validating single checkboxes. If you need to do this, say for a terms ang conditions agreement or something, you have to check that the value is greaterthan zero.

To do this, add a validator like this:

 $e =new Zend_Form_Element_Checkbox('tnc');
$e->addValidator('GreaterThan', false, array(0));

And validate your form in the controller as usual

 if ($form->isValid($request->getPost())) {

Thanks to Rob Knight for adding how to do this in the bug tracker. http://framework.zend.com/issues/browse/ZF-5920

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

 
 Comments
  1. admin says:

    Update.

    If you want to suppress the silly error message that zend gives:

    * ’0′ is not greater than ”

    Then do this:

    $validator = new Zend_Validate_GreaterThan(false, array(0));
    $validator->setMessage(”,
    Zend_Validate_GreaterThan::NOT_GREATER);
    $e->addValidator($validator, false, array(0));

  2. Hey,

    To overcome this problem. I used the the below code;

    $terms =
    $this->createElement(‘checkBox’, ‘terms’, array(
    ‘required’ => true,
    ‘checkedValue’ => ’1′,
    ‘uncheckedValue’ => ’0′
    ))
    ->addValidator(‘GreaterThan’, false, array(0))
    ->addErrorMessage(“Please agree with terms and conditions.”);

Leave a Reply