Welcome Guest, Not a member yet? Register   Sign In
Custom validation rule, variables on Model
#1

Hi, I have created a custom validation rule, it's like 'is_unique', but with an extra value...
So I can not only check whether a name already exists in the database, but I can check if a user already exists with a specific company_id.
I have added this rule to a model like this:
PHP Code:
    protected $validationRules = [
        'name'    => 'is_double_unique[users,name,company_id,{company_id},id,{id}]',
        'id' => 'permit_empty',
        'company_id' => 'permit_empty'
    ]; 



For INSERTS this works great... But UPDATES always get through, even on duplicates.
I noticed that when the 'company_id' doesn't change (but the name does), the value of 'company_name' is '{company_name}'.
The user entity has a company_id, but it's not passed through to the validation rule because it's an unchanged value.
Resulting a query which checks where 'company_id = {company_id}' instead of 'company_id = 4' for example.

How can I include the data of the unchanged fields as well?
Reply
#2

See the Important note in https://codeigniter.com/user_guide/model...validation
Reply
#3

Thanks, that was it.

The docs states a warning: "This is to avoid validation errors when updating only some fields.".

But in which scenario would 'false' for $cleanValidationRules trigger a validation error which is false?
Reply
#4

By default, if you use an Entity, only changed field data is passed when updating to the database.
So if a required field is not changed, the field is not passed to Validation, and it returns a validation error.
See https://codeigniter.com/user_guide/model...nlychanged
Reply
#5

So if I equip all my models with:

$updateOnlyChanged = false;
$cleanValidationRules = false;

It should be OK right?
Reply
#6

No problem.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB