I've looked quite thoroughly through previous questions and I'm surprised that nobody else has asked this yet because it seems like a pretty simple thing.
How do I make my labels wrap the inputs as well as the label text using CakePHP's FormHelper? I am using CakePHP 2.3.1. A call to $this->Form->radio()
with some standard options yields:
<input id="input_id" type="radio" ... />
<label for="input_id">label text</label>
What I'm looking for is
<label for="input_id"><input type="radio" id="input_id" ... />label text</label>
I have achieved this sort of using:
$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 anybody tell me if CakePHP has an easier and "more proper" way to achieve this?
I came across this whilst trying to find the answer myself and solved it. You don't need to alter/extend the class; it can be acheived purely through passing the appropriate options.
This is what I did so it works 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 put each radio in its own <div class="radio">
to comply with bootstrap markup. If you just want the simple label wrapping remove the div
elements from before
, after
and separator
Extend the helper, and make 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 into your own helper here...
P.S. if you're just adding a single method, it's not likely you'll need an entire helper. Just add the function "display" to app_helper.php and reference it from any "other" helper you already loaded, since they extend app_helper, you'll have the display method available in all the child helpers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With