[SOLVED] Connecting checkboxlist to database

This is in my form.php:

<?php $checkbox = [ 'hello', 'hello2', 'hello4', ]?>
            <?= $form->field($model,'Cvalues')->checkboxList($checkbox, ['prompt' => 'Select Your Country'])?>

This is in my NewUser.php:

[[‘username’, ‘password’, ‘mobile’, ‘address’, ‘type’, ‘category’, ‘country’, ‘Cvalues’], ‘required’],

        [['username', 'password', 'mobile', 'address', 'type', 'category', 'country', 'social'], 'string', 'max' => 255],

        [['Cvalues'], 'string', 'max' => 100],

And also when i click the checkboxlist and click register i have this error: Cvalues must be a string.

Thank you in advance :slight_smile: .

You need to know, that checkboxList() will return an array, because you can select multiple options in it; for examle if you check “hello1” and “hello2” you will get:

[“hello1”, “hello2”]

or if you select “hello3” only, you will get:

[“hello3”]

That’s why you are getting this error. If you want to select multiple values:

 public function rules() {
         return [
             [['Cvalues], 'safe'],
         ];
     }

Add this in your beforeSave() - it will save your array as a string:

if ($this->Cvalues&& count($this->Cvalues)) {
      $this->Cvalues= Json::encode($this->Cvalues);
}
1 Like

where will i put that

    public function beforeSave($insert) {
          if ($this->Cvalues&& count($this->Cvalues)) {
               $this->Cvalues= Json::encode($this->Cvalues);
          }
          return parent::beforeSave($insert);
    }

Paste it in your model.

it still gives me the error cvalues must be a string

Did you change:

[['Cvalues'], 'string', 'max' => 100],

to:

[['Cvalues], 'safe'],

thank you so much :slight_smile: !!!

1 Like