2

I have a model wich checks a lot of things in beforeSave callback. I do not want to use cakephp validation system for that purpose because it is more simple for me in this case.

If the checking chain fails in somewhere I return false and no saving happens, It is the normal work. I want to give back informal error messages in the entity to use it in the controller and/or view.

How I can do that? Example:

public function beforeSave($event, $entity, $options)
{
    if($entity->isNew())
    {
        if(fail1) $entity->inserterrormessage('XYZ is missing');
        if(fail2) $entity->inserterrormessage('Please check if...');
    }
}
ndm
  • 59,784
  • 9
  • 71
  • 110
sipiatti
  • 904
  • 1
  • 9
  • 21

1 Answers1

3

How I can do that?

Via the errors() method, or as of CakePHP 3.4 the setError() and setErrors() methods.

$entity->errors('propertyName', ['Message']);
$entity->setErrors(['propertyName' => ['Message']]);
$entity->setError('propertyName', ['Message']);

In case the error isn't related to an actual entity property, just choose a special name, like _generic. Alternatively create custom generic error storage functionality in a base entity or trait.

See also

ndm
  • 59,784
  • 9
  • 71
  • 110