2017-03-17 124 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')。所以你的回答將提高我對使用模型的理解。 –

相關問題