2017-03-17 68 views
1

我有一个_form如何在yii2中创建表单后使用更新?

<?php $form = ActiveForm::begin(); ?> 
    <?= $form->field($model, 'result')->textInput(['maxlength' => true]) ?> 
    <?= $form->field($model, 'test1')->textInput(['maxlength' => true]) ?> 
    <?= $form->field($model, 'test2')->textInput(['maxlength' => true]) ?> 
<?php ActiveForm::end(); ?> 

<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 

我需要设置一个公式:结果=测试1 *测试2

使用原始的SQL我可以把它放在控制器:

public function actionIndex(){ 
    Yii::$app->db->createCommand("UPDATE table1 SET result = test1*test2")->execute(); 
etc... 
} 

而且没关系。但我认为这是不正确的。因此,要做到这一点,最好的办法是:

 public function actionTest($id) 
     { 
      $model = $this->findModel($id); 
      $model->result = $model->test1 * model->test2 
     } 

后:

<?= Html::a('gotest', ['test', 'id' => $model->id], ['class' => 'btn btn-success']) ?> 

但我怎么能得到$model->id从形式创造的actionIndex?或者也许是其他选择?

回答

1

我认为一个干净的方式Yii2做到这一点应该使用afterFind回调与计算值来填补你的result领域,如:

在你型号

public function afterFind() 
{ 
    $this->result = $this->test1 * $this->test2; 
} 

所有你在中输入的逻辑将在Yii2从DB获得结果后立即执行。在放入表单或DataProvider之前需要计算某些内容时,这很好,因为所有内容都将在模型中正确执行。

如果我得到这个权利,你甚至不需要数据库中的结果字段。 (这样,只需在你的模型中声明它,创建一个像这样的虚拟字段:public $result;,你就可以使用它,就像它存在于表格中一样

+1

在这种情况下,我需要结果在数据库中。 'afterFind()'工作得很好,我在一分钟前测试过,并且用'public $ result;'添加虚拟字段非常有趣,我认为这将是另一个任务所必需的。例如'checkboxList()'并插入数据库单元格(使用'implode')。所以你的回答将提高我对使用模型的理解。 –

相关问题