B
B
Belka20072018-10-27 14:49:37
Yii
Belka2007, 2018-10-27 14:49:37

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_2and 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');
  }
}

Or create a separate model for the form:
$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');
  }
}

But somehow this is all not according to Feng Shui ... maybe there is a more correct / concise way, through scripts or something else?
PS: In reality, there are many fields in the tables that need to be allowed to be filled and many that need to be prevented from being overwritten.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-10-27
@Belka2007

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)) {
        *****
    }
}

Moreover, validation in the save() method is enabled by default.
public boolean save ( $runValidation = true, $attributeNames = null )

M
Maxim Timofeev, 2018-10-27
@webinar

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.

In theory, for each form you will either have your own model or scripts that will form custom validation rules. If this is a form for adding a product that the user fills out, then it is reasonable to make a regular model that is inherited from Model, and not from ActiveRecods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question