Zend_Form radio element
Asked Answered
C

2

8

Below is sample code to create a radio button element with Yes/No options in Zend_Form. Any ideas on how to set the required answer to Yes, so if No is selected, it'll fail validation? The code below will accept either Yes or No.

    $question= new Zend_Form_Element_Radio('question');
    $question->setRequired(true)
        ->setLabel('Are you sure?')
        ->setMultiOptions(array('Yes', 'No'));
Coseismal answered 16/1, 2009 at 22:8 Comment(0)
C
6

Not sure if this is the best way, but it worked for me:

$questionValid = new Zend_Validate_InArray(array('Yes'));
$questionValid->setMessage('Yes is required!');

$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
    ->setLabel('Are you sure?')
    ->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
    ->addValidator($questionValid);
Cobbler answered 16/1, 2009 at 22:23 Comment(0)
T
0

A quicker way, though this wouldn't work for other situations:

$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
    ->setLabel('Are you sure?')
    ->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
    ->addValidator('StringLength', false, array('min' => 3, 'messages' => "You must be sure."));

Since "no" is less than 3 characters, this will fail unless "yes" is selected. It's a little "hacky", but I like this way because it uses less code and also makes use of the built-in validators.

Taitaichung answered 27/2, 2013 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.