Sunith Saga
Sunith Saga

Reputation: 609

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

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

Upvotes: 6

Views: 24410

Answers (5)

Kailas
Kailas

Reputation: 3231

Follow the below link

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

I hope the link is useful.

Upvotes: 2

Samuel Liew
Samuel Liew

Reputation: 79022

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
}

Upvotes: 4

Michael H&#228;rtl
Michael H&#228;rtl

Reputation: 8587

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

public $label_name = true;

Upvotes: 1

Sunith Saga
Sunith Saga

Reputation: 609

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

Upvotes: 8

Kapil gopinath
Kapil gopinath

Reputation: 1053

Your requirement is to keep the checkbox checked for both create and update. checked=checked will serve the purpose on create form but , on updating you have to handle it through code

Upvotes: 0

Related Questions