Zend Form Radio Default

I have the following switch 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 to install a tuned radio? Now when I open my script, no radio is selected. I want to select yes. How?

Thanks.

+4
source share
6 answers

it is much 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"); 
+7
source

In case someone is wondering, I use array notation to declare all my elements in my forms, and in zend framework 2 - by default, selected in the switch, you must add the attribute value and make it the option_value key that you want to choose 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 bit confusing because they used numeric keys in the parameter values ​​(0, 1), so when I saw "value" => 1, it was not obvious to me that it was the key in the value_options array. Hope this helps someone.

+7
source

Use this:

 ->setAttrib("checked","checked") 

So your complete code is as follows:

 $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 also use this:

 ->setValue('1') 

This will check the option represented by a value of 1 , which is yes .

+3
source

According to the manual, you would do it like this if you used the notation of the array: reference to the 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, ] ], ], ] ); 
+3
source

I found that if you have a set of filters, then ->setvalue('X') does not work.

I deleted ->addFilter('StringToLower')
and added ->setSeparator('')->setValue('N');

Worked with pleasure

+1
source

Yes. I resolved this with jQuery:

 jQuery(document).ready(function(){ var $radios = $('input:radio[name=enabled]'); if($radios.is(':checked') === false) { $radios.filter('[value=1]').attr('checked', true); } }); 
0
source

All Articles