Conditional Model

What would be the best approach to having a system in place and running for over a year and then adding a new field to the table. I would like this new field to be ‘required’ for any new entry, but not existing ones.

Is my only solution using javascript/jQuery, or is this something that can be dealt with through yii?

You can define rules in model the way you need.

I see I can use scenarios, but not sure how I can implement it here.

In my case the entire thing would be controlled by another field (the PK), If ProjectID > 51000 then make StatusId Required, otherwise, not. Could you elaborate on how this could be defined?

You can make custom validation. How your pk is incremented? Does it have auto increment in db or you manually set the id. For ProjectID > 51000. Some records may be removed before but your pk is on 51001 or something else. Does it matter in validation?

I would take the following approach:
Make the new field a NULL column in the db.
Use a validation rule with “when” function (and whenClient if necessary). Check $model->isNewRecord, + $model->id > x, or $model->created > date, or whatever your exact properties are that can be used to exclude old records.

This way users can update old records without having to add the new property, and new ones will require it.

search for “yii2 custom validator” and you will find what you need.

1 Like

@InsaneSkull
Yes, my PK is an AutoIncrement. Records should never be removed, but one way or another my PK is currently at 51000 and I want all future entries to have this required.

@glyph
Thank you, I will look into this further.

@DBCreator, @glyph suggested the correct way then.

Thank you both.

I was able to locate the proper documentation (under the heading Conditional Validation) and understand yet one more powerful aspect of Yii.

I’ve always liked Yii, but the more I work with it, and get help from people like yourselves, the more I love it!