is_unique rule validation in Codeigniter 4 throws non-unique error when updating record
P粉617597173
P粉617597173 2024-01-10 16:31:46
0
1
458

I have a simple form that stores some data in a database, and for the Title field I have a is_unique validation rule along with other rules. Here are my TaskModel validation rules:

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, when adding data to the database, everything runs as expected. The problem is that when I try to update the record, let's say I change the author name, when I submit the form it says the title should be unique. I want it to ignore the row of records in the database I'm editing and check the uniqueness of the input with others. Can you help me achieve this? I'm thinking of passing the record ID through the form and ignoring it when checking for uniqueness, but I don't know how to pass the ID to the validation rule.

P粉617597173
P粉617597173

reply all(1)
P粉752479467

You can pass the ID of the row as a parameter to the is_unique rule. like

is_unique[tasks.Title,Id,{Id}]

Hope this helps :)

Update: More detailed instructions

The second parameterId is the name of the database field. The third one is the Id passed from the form. To do this, add a hidden field to the edit form and set its name = Id and its value=$data['Id']. where $data['Id'] is the Id of the row obtained from the database and passed to the view. So when the form is submitted, the Id will be submitted in $_POST. Then pass it to the rule parameters: {Id}

Hope this helps :(

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!