How to prevent form manipulation with validation rules

I want to create a form for a model that has some default values inside validation rules.

public function rules()
    {
        return [
            [['city', 'area'], 'required'],
           // this
            ['status', 'default', 'value' => self::STATUS_PENDING_REVIEW]
        ];
    }

In my form I have inputs for everything else except status field however I noticed that if someone changes the input’s name from the inspector from let’s say city to status then they can directly update the status field inside the database.

I can think of several ways to prevent this. I just wanted to ask if there is a built-in or a recommended/best practices way to do this.

What I was thinking was extending the original model and create a DTO like model that allows only the right fields to go through the form. But for me that means I have to create a lot those dtos because I have different scenarios.

Also I tried doing this with a scenario like the following but it skips validation for default values entirely.

public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_CREATE] = array_merge(parent::rules(), ['city', 'area']);
        return $scenarios;
    }

Any help is appreciated! :heart:

  1. Remove the rule for status from rules().
  2. Set field value directly as the property default.

That works if you’re using a form model and not reusing active record for the form. It’s not a good practice anyway…

I ended up creating a MyModelForm extending yii\base\Model class that has its own save function which handles saving and updating for that model. So I removed any validation from the base model so it doesn’t do the validations twice.

1 Like