Zend Form Radio Default Checked
Solution 1
it is much more easier :)
$enabled = $this->createElement('radio', 'enabled')
->setLabel('Enabled')
->setMultiOptions(array('1'=>'yes', '0'=>'no'))
->setValue($rank_values['enabled'])
->setAttrib('id', 'enabled')
->setAttrib('class', $action . '_enabled')
->setSeparator('')
->setValue("1");
Solution 2
In case somebody wonders, I'm using the array notation to declare all my elements in my forms and in zend framework 2 to have a default option selected in a radio button you have to add the attribute value and make it have the key of the value_options you want to be selected by default:
// Inside your constructor or init method for your form //
$this->add(
[
'type' => 'Radio',
'name' => 'some_radio',
'options' => [
'value_options' => [
'opt1' => 'Radio option 1',
'opt2' => 'Radio option 2'
]
],
'attributes' => [
'value' => 'opt1' // This set the opt 1 as selected when form is rendered
]
]
);
I found some examples a little confusing because they were using numeric keys in the value options (0, 1) so when I saw 'value' => 1 it wasn't obvious for me that this was the key in the value_options array. Hope this helps someone.
Solution 3
Use this:
->setAttrib("checked","checked")
So that your complete code looks like this:
$enabled = $this->createElement('radio', 'enabled')
->setLabel('Enabled')
->setMultiOptions(array('0'=>'no', '1'=>'yes'))
->setAttrib("checked","checked")
->setValue($rank_values['enabled'])
->setAttrib('id', 'enabled')
->setAttrib('class', $action . '_enabled')
->setSeparator('');
[EDIT] Using setValue
:
You can alternatively use this:
->setValue('1')
This will check the option represented by value 1
which is yes
.
Solution 4
According to the manual, you would do it this way if you were to use array notation: link to manual
$this->add(
[
'name' => 'someRadioMethod',
'type' => 'radio',
'options' => [
'label' => 'Some descriptive label',
'value_options' => [
[
'value' => '1',
'label' => 'Label for 1',
'selected' => true,
],
[
'value' => '2',
'label' => 'Label for 2',
'selected' => false,
]
],
],
]
);
Solution 5
I found that if you have a filter set then ->setvalue('X')
does not work.
I removed ->addFilter('StringToLower')
and added ->setSeparator('')->setValue('N');
Worked a treat
Alex Pliutau
Updated on February 22, 2020Comments
-
Alex Pliutau about 4 years
I have the next radio button group:
$enabled = $this->createElement('radio', 'enabled') ->setLabel('Enabled') ->setMultiOptions(array('1'=>'yes', '0'=>'no')) ->setValue($rank_values['enabled']) ->setAttrib('id', 'enabled') ->setAttrib('class', $action . '_enabled') ->setSeparator('');
How can I set a checked radio? Now, when I open my script, there are not selected radio. I want to select 'yes'. How?
Thank you.