Validating Models

Validating Data Integrity

Phalcon\Mvc\Model provides several events to validate data and implement business rules. The special validation event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation.

The following example shows how to use it:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Validation;
  5. use Phalcon\Validation\Validator\Uniqueness;
  6. use Phalcon\Validation\Validator\InclusionIn;
  7. class Robots extends Model
  8. {
  9. public function validation()
  10. {
  11. $validator = new Validation();
  12. $validator->add(
  13. 'type',
  14. new InclusionIn(
  15. [
  16. 'domain' => [
  17. 'Mechanical',
  18. 'Virtual',
  19. ]
  20. ]
  21. )
  22. );
  23. $validator->add(
  24. 'name',
  25. new Uniqueness(
  26. [
  27. 'message' => 'The robot name must be unique',
  28. ]
  29. )
  30. );
  31. return $this->validate($validator);
  32. }
  33. }

The above example performs a validation using the built-in validator ‘InclusionIn’. It checks the value of the field type in a domain list. If the value is not included in the method then the validator will fail and return false.

For more information on validators, see the Validation documentation

The idea of creating validators is make them reusable between several models. A validator can also be as simple as:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Message;
  5. class Robots extends Model
  6. {
  7. public function validation()
  8. {
  9. if ($this->type === 'Old') {
  10. $message = new Message(
  11. 'Sorry, old robots are not allowed anymore',
  12. 'type',
  13. 'MyType'
  14. );
  15. $this->appendMessage($message);
  16. return false;
  17. }
  18. return true;
  19. }
  20. }

Validation Messages

Phalcon\Mvc\Model has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes.

Each message is an instance of Phalcon\Mvc\Model\Message and the set of messages generated can be retrieved with the getMessages() method. Each message provides extended information like the field name that generated the message or the message type:

  1. <?php
  2. if ($robot->save() === false) {
  3. $messages = $robot->getMessages();
  4. foreach ($messages as $message) {
  5. echo 'Message: ', $message->getMessage();
  6. echo 'Field: ', $message->getField();
  7. echo 'Type: ', $message->getType();
  8. }
  9. }

Phalcon\Mvc\Model can generate the following types of validation messages:

TypeDescription
PresenceOfGenerated when a field with a non-null attribute on the database is trying to insert/update a null value
ConstraintViolationGenerated when a field part of a virtual foreign key is trying to insert/update a value that doesn’t exist in the referenced model
InvalidValueGenerated when a validator failed because of an invalid value
InvalidCreateAttemptProduced when a record is attempted to be created but it already exists
InvalidUpdateAttemptProduced when a record is attempted to be updated but it doesn’t exist

The getMessages() method can be overridden in a model to replace/translate the default messages generated automatically by the ORM:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public function getMessages()
  7. {
  8. $messages = [];
  9. foreach (parent::getMessages() as $message) {
  10. switch ($message->getType()) {
  11. case 'InvalidCreateAttempt':
  12. $messages[] = 'The record cannot be created because it already exists';
  13. break;
  14. case 'InvalidUpdateAttempt':
  15. $messages[] = "The record cannot be updated because it doesn't exist";
  16. break;
  17. case 'PresenceOf':
  18. $messages[] = 'The field ' . $message->getField() . ' is mandatory';
  19. break;
  20. }
  21. }
  22. return $messages;
  23. }
  24. }

Validation Failed Events

Another type of events are available when the data validation process finds any inconsistency:

OperationNameExplanation
Insert or UpdatenotSavedTriggered when the INSERT or UPDATE operation fails for any reason
Insert, Delete or UpdateonValidationFailsTriggered when any data manipulation operation fails