Andi Crew
Andi Crew

Reputation: 129

How to use the update after create form in yii2?

I have a _form:

<?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']) ?>

I need to set a formula: result = test1*test2

Using raw sql I can put it in controller:

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

And it's ok. But I think it's not correct. So the best way to do this is:

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

after:

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

But how can I get $model->id from form create to actionIndex ? Or maybe other option?

Upvotes: 1

Views: 809

Answers (1)

Thiago Elias
Thiago Elias

Reputation: 939

I think a clean way to do this in Yii2 should be using afterFind callback to fill your result field with your calculated value, like this:

In your Model:

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

All logic you put in your afterFind will be executed just after Yii2 get the result from DB. It's nice when you need to calculate something before put in a form or a DataProvider, because everything will happens right in the model.

If I get this right, you won't even need the result field in your database. (in this way, just declare it in your model, creating an virtual field like this: public $result; and you'll be able to use it just like if it exists in table.

Upvotes: 1

Related Questions