CHtml Checkbox List

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


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

activeCheckBoxList With CHtml

CHtml activeCheckBoxList generates a checkbox list for a model attribute.

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

checkBoxList With Form

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

checkBoxList With CHtml (Without Model Name)

//syntax:CHtml::checkBoxList(string name, default_select_by_array_keys,array_value());
echo CHtml::checkBoxList('Typelist[name]',
echo CHtml::checkBoxList('Typelist[name]',$selected_Array=array(),$type_list);


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

checkBoxList Validation In Model

Add the validation to checkBoxList value in model.

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

checkBoxList Value In Controller

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

Selected checkbox List Value From Database

//already selected value
//all type list
echo CHtml::checkBoxList('typelist', $selected_type_list,$type_list);

checkbox List Style

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

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

    very nice & clear, thank you!

  • very nice and helpful

  • Resly

    Helpful. Thank You!

  • Budi Santoso

    Great sample! Thanks for sharing…

  • Ricardo Magaña

    I write the code to fill a cheklist from a table but only I get 1 record

    findAll(“estado = 1 and esjefe = 1”),’id’,’NombreCorto’); ?>
    checkBoxList($losCc,’Empleado_id’,$type_list); ?>


    • m bala

      Hi Ricardo,
      There is no more logic here. Just we fetch all the record using findAll() method. after We will convert to array using listData() and finally have to assign that array to checkBoxList().
      Please check your findAll() condition.

  • Ali Eren

    Hi .
    I want to create from chtml without model. I want to only 2 selection on checkboxlist but i dont apply limit for checkboxlist . How can do it?

    echo CHtml::checkBoxList(‘list_name’, $selected_ids, $data_list,