简体   繁体   中英

Yii2: How to get checkox's value from controller

I need to get the value of a checkbox called Password using the Yii2 Framework, in the controller.

In my _form.php I define the checkbox:

<?= Html::checkbox('password', false, $options = ['label' => 'Reset password']) ?>

In my UserController.php I have the actionUpdate function:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        echo '<pre>';
        echo Yii::$app->request->post()['password'];
        echo '</pre>';
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

I always get the value 1 instead of true or false .

First of all, there is error in your code, it should be:

<?= Html::checkbox('password', false, ['label' => 'Reset password']) ?>

This checkbox generates 1 when checked by default. If you want to send 0 when checkbox is not selected you must add:

<?= Html::checkbox('password', false, ['label' => 'Reset password', 'uncheck' => 0]) ?>

Checkbox return 1 for true(checked) and return 0 for false(not checked).

You can check in controller as below

if(isset($model->password) && $model->password =="1") //check box is checked
{
     // code
}

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