首页 > 解决方案 > 根据表单php上的检查字段选择数据库中的某些字段

问题描述

我有表名 Checkin 字段:id、chief_compain、taken_history、pass_history、physical_exam 和诊断。

我想在表单上使用复选框属性作为表“签入”中的字段名称,因此在提交表单后将仅选择从数据库中选择的列名称。

    <?php $form = ActiveForm::begin(); ?>
        <?= $form->field($model, 'id')->checkbox(['value'=>Yii::$app->request->get('id')]) ?>
         <?= $form->field($model, 'chief_compain')->checkbox(['value'=>'chief_compain']) ?>
        <?= $form->field($model, 'taking_history')->checkbox(['value'=>'taking_history']) ?>
        <?= $form->field($model, 'pass_history')->checkbox(['value'=>'pass_history']) ?>
        <?= $form->field($model, 'physical_exam')->checkbox(['value'=>'physical_exam']) ?>
        <?= $form->field($model, 'diagnosis')->checkbox(['value'=>'diagnosis']) ?>

    <div class="form-group text-center">
            <?= Html::submitButton($model->isNewRecord ? 'Submit' : 'Save Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>
        </div>
      <?php ActiveForm::end(); ?>




    // === Controler 

    public function actionMedicalReport()
        {

            $model = new CheckIn();

            if ($model->load(Yii::$app->request->post()) ) {
                  $id=Yii::$app->request->post('id');
    $string = '';
            foreach (\Yii::$app->request->post() as $key => $value){
    if($value){
                    $string .= $key . ' ';
                    var_dump($string);
                }
            }

    $report=CheckIn::find()->select($string)->where(['id'=>$id])->all();
    return $this->render('print-report', ['report' => $report,]);

            } else {
                return $this->render('medical-report', [
                    'model' => $model,
                ]);
            }
        } 

标签: phpyii2

解决方案


好的,在 Yii2 表单中你不能这样提交。您必须使用 ActiveForm 小部件或插入带有令牌的隐藏字段,ovirwize 您将获得异常。第二:如果您通过 POST 或 GET 传递数据,您可以使用循环轻松检查它。因为您使用复选框,所以我假设您在整个帖子中传递并且值为真或假。

$string = '';
foreach (\Yii::$app->request->post() as $key => $value){
    if($key !== '_csrf-backend' && $value){
        $string .= $key . ' ';
    }
}

之后,您创建新的查询,或者您可以在循环之前实现该查询并在循环中传递所需的字段。我强烈建议不要使用原始 sql。


推荐阅读