I have a time sheet form which users enter time sheet for employee. In the form, there is a "Employee" dropdown, I put a unique validator on the "Employee" so that if users try to select Employees whose time already entered, the form will display error so users do not enter more than 1 entry for each employee.
It works great for "Create" new entry, but "Update" does not work because the unique validation fails.
I can restrict the unique validation check on "Create" only but what if users update Employee B timesheet but change Employee B to Employee A.
So I want a solution that
on Create, check if this employee already has time entry entered
on Update, if I dont change the employee, the unique test should skip. If I do change the employee, the unique test should run.
but I think you can achieve that with a scenario for the specific attributeā¦
Lets say you call the scenario for validating the unique attribute "isUserUnique".
Normally when you run your validation you are following a procedure like for example:
Create a model instace with the "isUserUnique" scenario.
Fill the model with POST data.
Validate & Save the model.
Right?
I think the trick would be something like:
Load existing model from DB for update.
Simple code (not executable but for understanding)
// when the user in the existing model is NOT the same like posted by the form
// then change the model scenario to "isUserUnique" to ensure the "new" user is unique
If($myModel->user != $_POST["user_id"]){
$myModel->scenario = "isUserUnique";
}
// validation or other code here
$myModel->save();
So in above example the "user unique" would only be checked if the user has changed.