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.

CheckBox

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)

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

OUTPUT HTML

<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')); ?>

OUTPUT HTML

<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.

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

Get Checkbox Value In Controller

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

Leave a Reply

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