Reputation: 107
I have a basic Yii2 application in which the user can create meals with a status (enum open or closed). The idea is that there should be only 1 record with the status open. Is there a simple way in Yii2 to check if there is already a record with open status before adding the new record ?
Edit
Apologies for the unclear description of my problem.
What i'am trying to accomplish would look like this:
So when a new meal is made, the status either has to be closed, or the status of the entry with open has to be edited to be closed so that the new meal can be created with an open status
Upvotes: 0
Views: 71
Reputation: 495
As you only want one 'open' status record, why do you just make your logic simple. Before you insert a new record, update all other records status to 'closed', then save the new record.
You better forbide the 'update' action, then if you want an 'open' status record, just create one.
You even can forget the 'status', just use the lastest record as 'open' status record.
Upvotes: 1
Reputation: 25312
You should try something like this :
// add this custom validator to your model's rules
['status', function ($attribute, $params) {
if ($this->getIsNewRecord() && $this->$attribute === 'open' && Meal::find([$attribute => 'open'])->count()>0)
$this->addError($attribute, 'Error message.');
}],
Upvotes: 2