YII2提交具有给定模型值的表单

时间:2022-03-04 20:31:15

How to add default value to a model to save?

如何将默认值添加到要保存的模型?

+--------------+--------------+-
| Field        | Type         |
+--------------+--------------+-
| id           | int(11)      | ->auto increment
| grant        | double(12,2) |
| lcc          | double(12,2) |
| encoded_by   | int(11)      | ->foreign key from tbl_user
+--------------+--------------+-

here is the html form code.

这是html表单代码。

<?= $form->field($model, 'grant')->textInput() ?>

<?= $form->field($model, 'lcc')->textInput() ?>

the error I get on submit..

我提交的错误..

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (ncddp.tbl_sp_bub, CONSTRAINT tbl_sp_bub_ibfk_2 FOREIGN KEY (encoded_by) REFERENCES user (id)) The SQL being executed was: INSERT INTO tbl_sp_bub (grant, lcc) VALUES (2, 2)

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(ncddp.tbl_sp_bub,CONSTRAINT tbl_sp_bub_ibfk_2 FOREIGN KEY(encoded_by)REFERENCES user(id))正在执行的SQL是:INSERT INTO tbl_sp_bub (grant,lcc)VALUES(2,2)

I understand that there should be a value for the encoded by which is the current users id.

我知道编码的值应该是当前用户ID。

I tried this.

我试过这个。

<?= $form->field($model, 'grant')->textInput() ?>

<?= $form->field($model, 'lcc')->textInput() ?>
<? $model->encoded_by=yii::$app->user->identity->id ?>

and also this in the controller...

而这在控制器中......

public function actionCreate()
    {
        $model = new TblSpBub();
        $model->encoded_by=yii::$app->user->identity->id;//MY CODE
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
            ]);
        }
    }

but to no avail...

但无济于事......

1 个解决方案

#1


There is built-in behavior to solve this called BlameableBehavior. Here is usage for your case. Add this to your model:

有一个内置行为来解决这个问题,称为BlameableBehavior。这是你的用法。将此添加到您的模型:

public function behaviors()
{
    return [
        [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'encoded_by',
            'updatedByAttribute' => false, // Set it to false if you need automatically update it on create only
        ],
    ];
}

And no need to handle it manually.

而且无需手动处理。

#1


There is built-in behavior to solve this called BlameableBehavior. Here is usage for your case. Add this to your model:

有一个内置行为来解决这个问题,称为BlameableBehavior。这是你的用法。将此添加到您的模型:

public function behaviors()
{
    return [
        [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'encoded_by',
            'updatedByAttribute' => false, // Set it to false if you need automatically update it on create only
        ],
    ];
}

And no need to handle it manually.

而且无需手动处理。