I have a simple form that stores some data in the database and for the Title field I have an is_unique validation rule along with others. Following are my validation rules from the TaskModel:
protected $validationRules = [
'Title' => 'required|min_length[5]|max_length[15]|is_unique[tasks.Title]',
'Description' => 'required|max_length[300]',
'CreatedAt' => 'required',
'UpdatedAt' => 'required',
'DueDate' => 'required|ValidateDueDate[DueDate]',
'AssignedTo' => 'required',
'Author' => 'required'
];
Now everything is working as intended when adding data to the Database. The Problem is when I try to update a record let's say I change the author name and when I submit the form it says the title should be unique. I want it to ignore the record row from the database I am editing and check input's uniqueness with others. Can you help me achieve this? I am thinking of passing the record id with the form and ignoring it when checking uniqueness but I don't know how to pass the Id to the validation rule.
CodePudding user response:
You can pass the Id of row as parameter in the is_unique rule. Like
is_unique[tasks.Title,Id,{Id}]
Hope this helps :)
UPDATE: More Detailed Explanation
Second parameter Id is database field name. Third one is the Id that is passed from the form. For this purpose add a hidden field in the edit form then set its name = Id
and its value=$data['Id']
. Where $data['Id']
is the Id of the row fetched from the Database and passed to the view. So when the form will be submitted and Id will be submitted in $_POST
. Which is then passed to rule parameter as:
{Id}
HOPE THIS HELPS :(