Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make checkbox check by default in yii while using single form for create and update

Tags:

forms

yii

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

like image 454
Sunith Saga Avatar asked Apr 26 '13 07:04

Sunith Saga


4 Answers

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
like image 198
Sunith Saga Avatar answered Oct 11 '22 05:10

Sunith Saga


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
}
like image 33
Samuel Liew Avatar answered Oct 11 '22 05:10

Samuel Liew


Follow the below link

http://www.bsourcecode.com/2013/03/yii-chtml-checkboxlist

I hope the link is useful.

like image 23
Kailas Avatar answered Oct 11 '22 07:10

Kailas


All you need is to set the default value in the model:

public $label_name = true;
like image 24
Michael Härtl Avatar answered Oct 11 '22 07:10

Michael Härtl