novice_developer
novice_developer

Reputation: 131

Yii2: How to add validation rules to the model class dynamically?

As per the Yii2 docs validation rules can be applied either to the implicit properties (table fields) or to the userDefined properties.

Is there a way to create validation rules for the properties which are dynamically added to the model class ?

For example:

Let there be model class named 'Filter' and another model class named 'Category' - categories like laptop, palmtop, desktop etc. I may want to use trackpad area as one of the filter to the laptop category and diagonal length as one of the filter to palmtop category and so on. So in every case filter conditions vary according to the category I choose and I may want to add it to the model class Filter dynamically and a validation if the load via post was successful.

Upvotes: 2

Views: 3074

Answers (1)

Blizz
Blizz

Reputation: 8408

You can code the rules()-function to build an array of validation rules depending on the scenario and data input. It is not a requirement that this is a fixed array. Unfortunately doing it this way will leave you with validation issues on the frontend (should you need that), dynamic rules there don't work so well.

From the comments I gather that the biggest issue seems to be that the attributes are not loaded into the model. This is mainly because both load() and setAttributes() only fill attributes considered to be safe.

There are 2 methods to define an attribute as safe:

  • Give it a validation rule (at the very least safe)
  • Get it in the list of attributes returned by safeAttributes() (by overriding it)

Upvotes: 2

Related Questions