代码之家  ›  专栏  ›  技术社区  ›  Dubby

使用DynamicModel问题预填充checkboxList

  •  1
  • Dubby  · 技术社区  · 9 年前

    我创建了一个DynamicModel来构建一个搜索表单,其中包含一个复选框列表,其中的条目由模型的记录填充。表单工作正常,但是表单显示在结果页面上,除复选框列表外,所有字段都用以前选择的值填充。

    控制器:

        $model = DynamicModel::validateData(
                    ['date_from',
                     'date_to',
                     'client_site',
                     'report_types',
        ]);
        $model->addRule(['client_site'], 'integer');
        $model->addRule(['client_site', 'report_types'], 'required');
        $model->addRule(['date_from','date_to'], 'string');
    
        $model->load(Yii::$app->request->post()) && $model->validate();
    
        $reportTypes = ArrayHelper::map(ReportType::find()->asArray()->all, 'id', 'name');
    
        return $this->render('print-report-form', [
                                        'report_types' => $reportTypes,
                                        'model' => $model,
        ]);
    

    视图:

        <?= $form->field($model, 'report_types[]')
             ->inline(false)
             ->checkboxList($reportTypes);
        ?>
    

    我是否需要以另一种方式将$reportTypes绑定到模型中?关于为什么所选复选框未在表单提交中预先填充的原因,有什么想法吗?

    1 回复  |  直到 9 年前
        1
  •  1
  •   Sohel Ahmed Mesaniya    9 年前

    首先,视图表单字段中存在错误,变量名称错误,应该是

    <?= $form->field($model, 'report_types[]')
         ->inline(false)
         ->checkboxList($report_types);
    ?>
    

    然后在 controller

    $model = DynamicModel::validateData(
                ['date_from',
                 'date_to',
                 'client_site',
                 'report_types',
    ]);
    $model->addRule(['client_site'], 'integer');
    $model->addRule(['client_site', 'report_types'], 'required');
    $model->addRule(['date_from','date_to'], 'string');
    
    $posted_model = clone $model;
    $reportTypes = ArrayHelper::map(ReportType::find()->asArray()->all, 'id', 'name');
    
    if($posted_model->load(Yii::$app->request->post()) && $posted_model->validate())
    {
        // save data or do as per your requirement with $posted_model
        // if nothing to be done, and just rendering back to form then
        return $this->render('print-report-form', [
            'report_types' => $reportTypes,
            'model' => $model,  // line X
        ]);
    }
    else
    {
        return $this->render('print-report-form', [
            'report_types' => $reportTypes,
            'model' => $model, // line X
        ]);        
    }
    

    发生这种情况是因为当视图第一次渲染时,所有复选框都是空的,但当提交表单时,模型会被POSTed数据填满,即其所有属性都已设置,然后您总是在渲染POSTed模型,即模型中充满了数据。

    现在,在上述情况下,您没有渲染POSTed模型,而是始终渲染空的新模型。

    这就是需要空复选框的情况。

    第二种情况:

    如果需要预先填充复选框 去除 [] 表单字段中

    <?= $form->field($model, 'report_types')
         ->inline(false)
         ->checkboxList($report_types);
    ?> 
    

    并将X行替换为 'model' => $posted_model,

    在这里,您将看到填充的复选框