2016-02-10 23 views
1

我创建了一个DynamicModel来构建一个包含checkboxList的搜索表单,其中的项目由模型的记录填充。表单工作正常,但表单显示在结果页面上,并且所有字段都使用除checkboxList之外的先前选定的值填充。使用DynamicModel问题的checkboxList的预填充

控制器:

$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

首先,有鉴于表单字段错误,变量名是错误的,它应该是

<?= $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 
    ]);   
} 

这是怎么回事,因为当观点第一次渲染时,所有复选框都是空的,但是当提交表单时,模型会被POST数据填满,即所有的属性都被设置,然后总是渲染POST模型,即模型填充数据。

现在有了上面的情况,你不会渲染POST模型,你总是渲染空的新模型。

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

第二种情况:

如果您需要复选框被随后预填充 通过 'model' => $posted_model,

在这里,在表单字段

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

删除[]和替换线X你会得到填充复选框

+1

非常感谢你的回应。我可以通过从表单中的'report_types []'中删除''''来解决它。从文件传递到文件时,变量名称应该没有关系。克隆模型也是不必要的,但我很感激。我很迷茫。谢谢 – Dubby