CHtml Checkbox

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


activeCheckbox With CHtml

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

CHtml activeCheckbox generates a check box for a model attribute.

Checkbox With Form

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

Checkbox With CHtml (Without Model Name)

//syntax:CHtml::checkBox(string name, boolean checked=false,array());
echo CHtml::checkBox('LoginForm[attribute]',true,array()); 


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

Checked Properties

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

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


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

Checkbox Value

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

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

Checkbox Validation In Model

Add the validation to checkbox value.

// attribute boolean true or false
// attribute integer o or 1
array('attribute', 'boolean'),

Get Checkbox Value In Controller

//if checked, return 1;
//if unchecked, return 0;
echo $checkbox_value;

Leave a Reply

Your email address will not be published. Required fields are marked *