简体   繁体   中英

Save value of checkboxlist to db in yii2

I have a yii2 form which contain a checkbox list items which i made like this:

<?php $CheckList = ["users" => 'Users', "attendance" => 'Attendance', "leave" => 'Leave', "payroll" => 'Payroll'];?>

    <?= $form->field($model, 'MenuID')->checkboxList($CheckList,['separator'=>'<br/>']) ?>

Now what i need is to save the values in the database column as a comma separated value.

I tried to modify the create function in my controller in this way:

 public function actionCreate()
{
    $model = new Role();

    if ($model->load(Yii::$app->request->post())) {


        if ($model->MenuID != " ") {
           $model->MenuID = implode(",", $model->MenuID);                
        }
         $model->save();             
        return $this->redirect(['view', 'id' => $model->RoleID]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

But the values are not being saved in the database

You need to set your model rules() .

When you call $model->load(Yii::$app->request->post()); the framework call method setAttributes() with param $safeOnly = true . This method with param $safe = true check if attributes are safe or not according to the rules of model. If you haven't any rules on the model all attributes are considered unsafe so your model is not populated.

Add rules() on your model and your code works

class Role extends yii\db\ActiveRecord
{
    ...

    public function rules()
    {
        return [
            ['MenuID', 'your-validation-rule'],
        ];
    }

   ...

Some additional info

NB If you do not specify scenario in the rules the default scenario is 'default' and if during instantiate of model object you set scenario to another didn't work. My example:

You have the same rules as I wrote before and you run this code

...
$model = new Role(['scenario' => 'insert']);

if ($model->load(Yii::$app->request->post())) {
...

model is empty after load becouse any rules is founded in 'insert' scenario and your problem is back. So if you want a rule that work only in particular scenario you must add 'on' rules definition. Like this:

...
public function rules()
{
    return [
        ['MenuID', 'your-validation-rule', 'on' => 'insert'],
    ];
}
...

For more example and explanations visit:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM