I am using single form for creating and updating a form.I need checkbox checked by default in the following form
<div class="row" style='float:left;;margin-left:5px'>
<?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?>
<?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>'checked','style'=>'margin-top:7px;')); ?>
<?php echo $form->error($model,'label_name'); ?>
</div>
i am using above code to achieve the same purpose i am not getting the result as expected. While updating the form it shows checked even though it was unchecked
i got solution i worked with code itself please have a look
<div class="row" style='float:left;;margin-left:5px'>
<?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?>
<?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>($model->id=="")?true:$model->label_name),'style'=>'margin-top:7px;')); ?>
<?php echo $form->error($model,'label_name'); ?>
</div
A better solution would be to set the value in the controller:
public function actionCreate() {
$model = new ModelName();
if (isset($_POST[$model])) {
// ... save code here
}
else {
// checkboxes for label 'label_name' with value '1'
// will be checked by default on first load
$model->label_name = true; // or 1
}
$this->render('create', array(
'model' => $model,
));
}
Or better still, in the afterConstruct()
function in the model:
protected function afterConstruct() {
parent::afterConstruct();
$this->label_name = true; // or 1
}
Follow the below link
http://www.bsourcecode.com/2013/03/yii-chtml-checkboxlist
I hope the link is useful.
All you need is to set the default value in the model:
public $label_name = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With