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

YII2 submit a form with a given model value

如何将默认值添加到模型中进行保存?

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

这里是 html 表单代码。

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

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

我在提交时遇到的错误..

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)

我知道应该有一个当前用户 ID 编码的值。

我试过了。

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

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

还有控制器中的这个...

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,
            ]);
        }
    }

但无济于事...

有一个名为 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
        ],
    ];
}

而且无需手动处理。