unique validator

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.



I have no concrete code example,

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:

  1. Create a model instace with the "isUserUnique" scenario.

  2. Fill the model with POST data.

  3. Validate & Save the model.


I think the trick would be something like:

  1. Load existing model from DB for update.

  2. 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 


So in above example the "user unique" would only be checked if the user has changed.

Hope it is clear what I meanā€¦

Best Regards

I have a round about solution for this problem. Please check if it helps.

Step1: Create one more model variable in the model class as $checkCurrentUser.

Step2: Make changes to your rules() method as below,

public function rules(){

return [

['user','unique','on' => 'create'],


['user','validateUser','on'=>'update' ]



public function validateUser($attribute){

if ($this->user != $this->checkCurrentUser){

// check for uniqueness by means of query


else {

// do nothing



Step3: Populate this variable as the $user which you want to update before you render.