CHtml Radio Button List

Using CHtml class we are creating radioButtonList in yii framework. This post will help you to understand about how to create radioButtonList in different method, How to assign value, how to get radioButtonList value in controller, radioButtonList value from database, radioButtonList validation in model and radion button list style in yii framework.


Using below code, we can create radiobutton list in different way. And i added radiobutton list value from database and assigned static array.

activeRadioButtonList With CHtml

CHtml activeRadioButtonList generates a radiobutton list for a model attribute in yii framework.

echo CHtml::activeRadioButtonList($model,'name',array('1'=>'One','2'=>'Two')); 
echo CHtml::activeRadioButtonList($model,'name',$type_list); 

radioButtonList With Form

echo $form->radioButtonList($model,'name',array('1'=>'One','2'=>'Two')); 
echo $form->radioButtonList($model,'name',$type_list); 

radioButtonList With CHtml (Without Model Name)

//syntax:CHtml::radioButtonList(string name, default_select_by_array_keys,array_value());
echo CHtml::radioButtonList('Typelist[name]',$selected_Array=array(),array('1'=>'One','2'=>'Two')); 
echo CHtml::radioButtonList('Typelist[name]',$selected_Array=array(),$type_list);


<span id="Typelist_name">
    <input value="1" id="Typelist_name_0" type="radio" name="Typelist[name][]">
    <label for="Typelist_name_0">One</label>br<
    <input value="2" id="Typelist_name_1" type="radio" name="Typelist[name][]">
    <label for="Typelist_name_1">Two</label>

radioButtonList Validation In Model

Add the validation to radioButtonList value in model.

array('name', 'in','range'=>array(1,2)),

radioButtonList Value In Controller

We can retrieve selected value one by one using foreach() in controller and also we can use imploed() directly on this radiobutton name.

foreach($model->name as $radiobutton_id){
    echo $radiobutton_id;

Selected radioButton List Value From Database

Get the radiobutton list value from database for selected value array and all value

//selected value from db
//all type list from db
echo CHtml::radioButtonList('typelist', $selected_type_list,$type_list);

radioButton List Style

Normally radioButton will display one by one. We can change this style using labelOptions. See below code

echo $form->radioButtonList($model,'type',
            'style'=> '
                width: 60px;
                float: left;
  <div style="clear: both;"></div>

Radio Button List Ajax

Read About Radio button ajax submit form