phpvalidationcakephpcakephp-3.3

Dynamically change CakePHP 3 custom validation rule message


I've got a custom validation method that checks a field for token values to ensure that they are all present in the content. The method works fine, it validates as OK when all the tokens exist in the content and throws a validation error when one or more tokens are missing.

I can easily apply a validation error message to state that some of the tokens are missing when I attach my custom validation rule to my table in validationDefault(). However, what I really want to do is set a validation message that reflects which of the tokens haven't been set. How can I dynamically set the validation message in CakePHP 3? In CakePHP 2 I used to use $this->invalidate() to apply an appropriate message, but this no longer appears to be an option.

My code looks like this (I've stripped out my actual token check as it isn't relevant to the issue here):-

public function validationDefault(Validator $validator)
{
    $validator
        ->add('content', 'custom', [
            'rule' => [$this, 'validateRequiredTokens'],
            'message' => 'Some of the required tokens are not present'
        ]);

    return $validator;
}

public function validateRequiredTokens($check, array $context)
{
    $missingTokens = [];

    // ... Check which tokens are missing and keep a record of these in $missingTokens ...

    if (!empty($missingTokens)) {
        // Want to update the validation message here to reflect the missing tokens.
        $validationMessage = __('The following tokens are missing {0}', implode(',', $missingTokens));

        return false;
    }

    return true;
}

Solution

  • Read the API docs.

    Copy and paste:

    EntityTrait::errors()

    Sets the error messages for a field or a list of fields. When called without the second argument it returns the validation errors for the specified fields. If called with no arguments it returns all the validation error messages stored in this entity and any other nested entity.

    // Sets the error messages for a single field
    $entity->errors('salary', ['must be numeric', 'must be a positive number']);
    
    // Returns the error messages for a single field
    $entity->errors('salary');
    
    // Returns all error messages indexed by field name
    $entity->errors();
    
    // Sets the error messages for multiple fields at once
    $entity->errors(['salary' => ['message'], 'name' => ['another message']);
    

    http://api.cakephp.org/3.3/class-Cake.Datasource.EntityTrait.html#_errors