Checked和Unchecked值的复选框将提交给控制器

时间:2015-06-08 20:25:01

标签: checkbox yii2 uncheck

我有14个复选框,有些可能会被检查,用户可以根据需要取消选中它们。

<?php $form = ActiveForm::begin(); ?>

<h3>New Courses</h3>
<?= GridView::widget([
'dataProvider' => $ns_dataProvider,
'summary' => "{totalCount} courses",
'columns' => [
    [
        'label'=>'Register',
        'format' => 'raw',
        'value'=>function ($data) use($student, $active_session_semester) {
           // return Html::a(Html::encode("Register"),'site/index');
            $studentsubject = \app\models\Studentsubject::find()->where([
                'student_id' => $student->id,
                'subject_id' => $data->id,
                'level_id' => $student->current_level_id,
                'session_semester_id' => $active_session_semester->id,
            ])->all();
            $countstudentsubject = count($studentsubject);


            if ($countstudentsubject > 0) {
            return Html::checkbox('subject_id[]',true,['uncheck'=>"r".$data->id,'value'=>$data->id]);}
            else {
                return Html::checkbox('subject_id[]', false, ['uncheck'=>"r".$data->id,'value' => $data->id]);
            }
        },
    ],

    'subject_title',

   ],
    ]); ?>
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

我检索了这个复选框的值

 if (Yii::$app->request->post()) {
        $x = Yii::$app->request->Post();
        $subject_ids = $x['subject_id'];
        var_dump($subject_ids);
  }

但是我得到这个,因为数组返回了16个值而不是14:

   array (size=16)
    0 => string 'r273' (length=4)
    1 => string '273' (length=3)
    2 => string 'r274' (length=4)
    3 => string '274' (length=3)
    4 => string 'r275' (length=4)
    5 => string 'r295' (length=4)
    6 => string 'r296' (length=4)
    7 => string 'r297' (length=4)
    8 => string 'r423' (length=4)
    9 => string 'r424' (length=4)
    10 => string 'r425' (length=4)
    11 => string 'r590' (length=4)
    12 => string 'r591' (length=4)
    13 => string 'r592' (length=4)
    14 => string 'r593' (length=4)
   15 => string 'r594' (length=4)

当我选中一个复选框时,会发送已选中和未选中的值。我错过了什么吗?对yii2来说还是比较新的。任何建议,建议和解决方案都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

在您的模型中,有一个包含16个值的复选框,并且提交将返回所有这些值,选中或取消选中这些值的事实并不意味着它们不会被提交。这不是Yii2问题。这是POST提交方法的正常行为