Get my inputs inside my labels using the CakePHP method FormHelper :: radio ()

I carefully studied the previous questions, and I am surprised that no one has asked about this yet, because it seems pretty simple.

How to make my shortcuts wrapped in inputs as well as label text using CakePHP FormHelper? I am using CakePHP 2.3.1. Calling $this->Form->radio() with some standard options gives:

 <input id="input_id" type="radio" ... /> <label for="input_id">label text</label> 

What I'm looking for

 <label for="input_id"><input type="radio" id="input_id" ... />label text</label> 

I used this method:

 $this->Form->input('input1',array('options'=>$options,'type'=>'radio', 'label'=>false 'before'=>'<label>', 'separator'=>'</label><label>', 'after'=>'</label>' )); 

But, obviously, this solution is not ideal. Can someone tell me if CakePHP has an easier and more β€œcorrect” way to achieve this?

+4
source share
2 answers

Extend the helper and create your own method.

 <?php // app/views/helpers/radio.php class RadioHelper extends AppHelper { function display($id, $options = array()) { if (isset($options['options']) && !empty($options['options'])) { $rc = ""; foreach ($options['options'] as $option) { $rc .= "<label>"; $rc .= "<input ....>"; $rc .= "</label>"; } return($rc); } return(false); // No options supplied. } } ?> 

 <?php // some_controller.php var $helpers = array('Radio'); ?> 

 <?php // some_view.ctp echo $this->Radio->display('input1', array('options' => $options)); ?> 

Just make sure you copy the logic from the form helper to your own helper ...

PS if you just add one method, you are unlikely to need the whole helper. Just add the "display" function to app_helper.php and reference it from any "other" helper that you have already downloaded, since they extend the app_helper application, you will have a display method available in all child helpers.

+4
source

I stumbled upon this, trying to find the answer and solving it. You do not need to modify / extend the class; this can only be achieved by passing the appropriate parameters.

This is what I did to make it work with bootstrap:

 $options = array( '1' => 'One', '2' => 'Two' ); $attributes = array( 'class' => '', 'label' => false, 'type' => 'radio', 'default'=> 0, 'legend' => false, 'before' => '<div class="radio"><label>', 'after' => '</label></div>', 'separator' => '</label></div><div class="radio"><label>', 'options' => $options ); echo $this->Form->input('myRadios', $attributes); 

This will cause each radio in its own <div class="radio"> to correspond to the markup of the download. If you just want simple label wrapping to remove div elements from before , after and separator

+14
source

All Articles