Zend Form - FormRadio defaults to 0

For programming and general questions on Zend Framework
Post Reply
noisemc
Posts: 12
Joined: Wed Nov 23, 2011 8:12 pm

Zend Form - FormRadio defaults to 0

Post by noisemc » Fri Jan 06, 2012 1:45 pm

Hello,

I have a radio buttons with 2 values: 1 and 0
I do not setValue() on this field so it should not have any radio button checked.

But if one of buttons have value of 0 and there is no value set for this control it automatically defaults to 0 (which is No in my case)

I found a problem in Zend_View_Helper_FormRadio line 157:

Code: Select all

$checked = '';
if (in_array($opt_value, $value)) {
    $checked = ' checked="checked"';
}
In my case
$value = array
(
[0] =>
);

$opt_value = 0;

Result of this conditional statement is true UNLESS I change it to:

Code: Select all

$checked = '';
if (in_array($opt_value, $value, true)) { // strict comparison
    $checked = ' checked="checked"';
}
I use latest version of ZF.

Should I report is as bug? Or maybe there is other way to go around this.
I would like not to use hacks like $element->setValue(-1);

ilians
Posts: 43
Joined: Fri Nov 04, 2011 8:29 am

Re: Zend Form - FormRadio defaults to 0

Post by ilians » Fri Jan 06, 2012 2:12 pm

I don't think it's a bug, just a choice they made designing the class.
If you don't want either of your radiobuttons checked, just don't use 0 as a key in your options.

Alternatives could be:

Code: Select all

$radio->addMultiOptions(array('option0'=>'No' , 'option1'=>'Yes'));
$radio->addMultiOptions(array('1'=>'No' , '2'=>'Yes'));

jschoenwolf
Posts: 239
Joined: Tue Aug 23, 2011 10:56 am

Re: Zend Form - FormRadio defaults to 0

Post by jschoenwolf » Fri Jan 06, 2012 3:11 pm

it might help to change the "inArray" validator:
By default, this element registers an InArray validator which validates against the array keys of registered options. You can disable this behavior by either calling setRegisterInArrayValidator(false), or by passing a FALSE value to the registerInArrayValidator configuration key.

noisemc
Posts: 12
Joined: Wed Nov 23, 2011 8:12 pm

Re: Zend Form - FormRadio defaults to 0

Post by noisemc » Fri Jan 06, 2012 3:37 pm

Thank you for you answers but
@ilians: I need to be able to have 0 as answer and it must not be preselected by default.
@jschoenwolf: This is not about validating answers but making radio button "checked"

And I think this is not intended "choice", it happens a lot because of annoying PHP feature which is 0 == false == "" == null

noisemc
Posts: 12
Joined: Wed Nov 23, 2011 8:12 pm

Re: Zend Form - FormRadio defaults to 0

Post by noisemc » Mon Jan 09, 2012 7:32 pm

Issue has been reported a year ago.
I just posted patch file:
http://framework.zend.com/issues/browse/ZF-8587

Not sure who actually commits this to svn and makes it to the release...

Post Reply