Answer the question
In order to leave comments, you need to log in
How in Yii2, when editing a model, to prevent overwriting fields that are not in the form?
For example, let's take that there are 4 fields in the "Products" table: field_1, field_2, field_3, field_4
.
When adding a new product (for example, in the admin panel), they are all present in the form and all are saved when the form is submitted.
And in the public part of the site, editing the product is available, but only 2 fields field_3, field_4
.
If you just create a form with 2 fields field_3, field_4
, then the attacker, knowing what other fields are there, can send the fields field_1, field_2
and they will be overwritten.
As an option, save the initial state of the model into a temporary variable and then explicitly overwrite fields that should not be changed from the form:
$model = $this->findModel($id);
$temp = clone $model;
if ($model->load(Yii::$app->request->post())) {
$model->field_1 = $temp->field_1;
$model->field_2 = $temp->field_2;
if ($model->save()) {
return $this->redirect('test');
}
}
$form = new ProductUpdateForm;
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
$model = $this->findModel($id);
$model->field_3 = $form->field_3;
$model->field_4 = $form->field_4;
if ($model->save(false)) {
return $this->redirect('test');
}
}
Answer the question
In order to leave comments, you need to log in
Good afternoon.
I would turn my attention to "scripts".
One script for creating a new entry, the second for editing an existing one.
Appropriate validation rules for each scenario.
https://www.yiiframework.com/doc/guide/2.0/en/stru...
ps
But what about RBAC?
PSS
Doesn't make sense and can lead to validation errors.
if (******** && $form->validate()) {
******
if ($model->save(true)) {
*****
}
}
public boolean save ( $runValidation = true, $attributeNames = null )
If you simply create a form with 2 fields field_3, field_4, then the attacker, knowing what other fields there are, can send the fields field_1, field_2 and they will be overwritten.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question