Saving a checkbox value in Yii

yii
45,528

Solution 1

For every input that you are accepting from user, you need to define it in model::rule(). is active defined there in rule()?

Solution 2

You can use htmlOptions array to specify value attribute. Below is the code example:

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

Since version 1.0.2, a special option named 'uncheckValue' is available that can be used to specify the value returned when the checkbox is not checked. By default, this value is '0'. (This text is taken from YII Documenration)

Solution 3

In general, if you are having problems saving to the database, i would replace

$model->save();

with

if($model->save() == false) var_dump($model->errors);

that way, you can see exactly why it did not save. it is usually a validation error.

Solution 4

Please follow: 1. in protected/models/Thing.php add active as a numeric

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('active', 'numerical', 'integerOnly'=>true),
            //OR optional 
            array('active', 'safe'),
    );
}

Controller action: Its ok

View:

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

Hope this will work for you...

Solution 5

Article which can be helpful when figuring out how to handle booleans & checkboxes in Yii

http://www.larryullman.com/2010/07/25/handling-checkboxes-in-yii-with-non-boolean-values/

Share:
45,528
Matt Hampel
Author by

Matt Hampel

Updated on March 19, 2020

Comments

  • Matt Hampel
    Matt Hampel about 4 years

    I can't figure out how to properly save checkbox values in Yii. I have a MySQL column, active, defined as a tinyint. I have the following form creation code, which correctly shows the checkbox as checked if the value is 1 and unchecked if 0:

        <?php echo $form->labelEx($model,'active'); ?>
        <?php echo $form->checkBox($model,'active'); ?>
        <?php echo $form->error($model,'active'); ?>
    

    And the code to save the form correctly changes other, text-based values:

    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
    
        if(isset($_POST['Thing']))
        {
            $model->attributes=$_POST['Thing'];
            if($model->save())
                $this->redirect(array('thing/index'));
        }
    
        $this->render('update',array(
            'model'=>$model,
        ));
    }
    

    The value of active is not saved. Where am I going wrong?