Skip to content
Advertisement

Yii – dynamically change rules from controller

Let’s say I have a product which can have a colour. Depending on the product type, the colour field may or may not be required.

If colour is always required, I would have the following in the product model

JavaScript

However, I want this to be dynamic depending on the product type.

Should this be done in the controller? I would imagine having something like the following in the controller:

JavaScript

What is the best way to approach this?

Thanks

Advertisement

Answer

You can use scenario. In the model:

JavaScript

And in the controller:

JavaScript

So, required colour will be validated when the model’s scenario is hasColour

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement