How to retain checkbox value when the screen reload?

I have been following this example


<?php echo $form->labelEx($model,'categories'); ?>

<?php echo $form->dropDownList($model, 'categories', CHtml::listData(

Categories::model()->findAll(), 'id', 'category'), array('multiple'=>'multiple', 'size'=>5)

); ?>

<?php echo $form->error($model,'categories'); ?>


But when the form is submitted with validation error, all my checkboxes ticks are gone. The rest of the input values persist.

What did I do wrong?


Im confused are we talking about checkbox? or dropdownlist?

Can you show me whats the output of print_r($model->categories) before and after the validation please?

I followed the example by Larry exactly except that I use checkBoxList and not dropdownlist.

if the form has no errors, I have no problem getting the values with :

     foreach ($_POST['Posts']['categories'] as $categoryId) {

                $postCategory = new PostsCategories;

                $postCategory->postId = $model->id;

                $postCategory->categoryId = $categoryId;

                if (!$postCategory->save()) print_r($postCategory->errors);


The problem is how to retain the user checkboxes before reached the db.

print_r($model->categories) will give an empty array when the form is reloaded upon validation error.


Can you please paste you action code? thanks.

Company Controller

    public function actionCreate()


        $model=new Company;







                foreach ($_POST['Company']['ports'] as $portId) {

                    $companyPort = new CompanyPort;

                    $companyPort->companyId = $model->id;

                    $companyPort->portId = $portId;

                    if (!$companyPort->save()) print_r($companyPort->errors);







                compact('model', 'modelPort'));


Views :

<div class="simple">

<?php echo Html::activeLabel($model,'name'); ?>

<?php echo Html::activeTextField($model,'name'); ?>


<div class="simple">

<?php echo Html::activeLabel($model,'portName'); ?>


<div style="float: left">

<?php echo Html::activeCheckBoxList($model,'ports', CHtml::listData($modelPort,'id','name')); ?>



I’m use to have the same problem.

but if i want to update and i want to retrieve all the values checked back in the update form

i didn’t figure out yet how it will be done " I’m always getting errors".

any help will be highly appreciated.