how add default value model save?
+--------------+--------------+- | field | type | +--------------+--------------+- | id | int(11) | ->auto increment | grant | double(12,2) | | lcc | double(12,2) | | encoded_by | int(11) | ->foreign key tbl_user +--------------+--------------+-
here html form code.
<?= $form->field($model, 'grant')->textinput() ?> <?= $form->field($model, 'lcc')->textinput() ?>
the error on submit..
sqlstate[23000]: integrity constraint violation: 1452 cannot add or update child row: foreign key constraint fails (
ncddp
.tbl_sp_bub
, constrainttbl_sp_bub_ibfk_2
foreign key (encoded_by
) referencesuser
(id
)) sql being executed was: inserttbl_sp_bub
(grant
,lcc
) values (2, 2)
i understand there should value encoded current users id.
i tried this.
<?= $form->field($model, 'grant')->textinput() ?> <?= $form->field($model, 'lcc')->textinput() ?> <? $model->encoded_by=yii::$app->user->identity->id ?>
and in 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 no avail...
there built-in behavior solve called blameablebehavior. here usage case. add model:
public function behaviors() { return [ [ 'class' => blameablebehavior::classname(), 'createdbyattribute' => 'encoded_by', 'updatedbyattribute' => false, // set false if need automatically update on create ], ]; }
and no need handle manually.
Comments
Post a Comment