CHtml Radio Button

Using CHtml class we are creating radioButton in yii. This post will help you to understand about how to create radioButton in different method, radioButton properties, array value, how to get radioButton value in controller and radioButton validation in model.

RadioButton

activeRadioButton With CHtml

<?php echo CHtml::activeRadioButton($model,'attribute',array()); ?>

CHtml activeRadioButton generates a radio button for a model attribute.

radioButton With Form

    <?php echo $form->radioButton($model,'attribute'); ?>

radioButton With CHtml (Without Model Name)

<?php 
//syntax:CHtml::radioButton(string name, boolean checked=false,array());
echo CHtml::radioButton('LoginForm[attribute]',true,array()); 
?>

OUTPUT HTML

<input name="LoginForm[attribute]" id="LoginForm_attribute" value="1" type="radio"?>

Checked Properties

if the radioButton values is 1, it will be checked otherwise unchecked.

<?php echo $form->radioButton($model,'attribute',array('checked'=>'checked')); ?>

OUTPUT HTML

<input type="radio" value="1" id="LoginForm_attribute" name="LoginForm[attribute]" checked="checked">

radioButton Value

We can change the radioButton value but we can assign only two values. They are value for checked radioButton and uncheckvalue for unchecked radioButton.

<?php echo $form->radioButton($model,'attribute',array('value' => '1', 'uncheckValue'=>'0')); ?>

radioButton Validation In Model

Add the validation to radioButton value.

 
<?php
// attribute boolean true or false
//OR
// attribute integer o or 1
  
array('attribute', 'boolean'),
?>

Get radioButton Value In Controller

<?php
//if checked, return 1;
//if unchecked, return 0;
.........
$radiobutton_value=$model->attribute;
echo $radioButton_value;
.......
?>