We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

ORM validation before my own validations

I'm trying to validate a a field name "my_field" using the classic public function validation() in my model. The ORM seems to validate it before. I only get "my_field is required". My function validation() is not even triggered.

Is there a way to make my validation fire before the one from the ORM?



2.6k

You could use the beforeValidation method. It is executed before the database validations are made.

Although intended I find it strange the user validation is run after the database validations/foreignkey checks.



26.3k
Accepted
answer

I'm trying to validate a a field name "my_field" using the classic public function validation() in my model. The ORM seems to validate it before. I only get "my_field is required". My function validation() is not even triggered. Is there a way to make my validation fire before the one from the ORM?

I switch off the default notNullValidations in the model. Do this in initialisation() method of the model. Check these post/docs:

(1) https://forum.phalcon.io/discussion/2547/give-custom-model-validation-priority

(2) https://forum.phalcon.io/discussion/1497/validation-with-presenceof-not-working

(3) https://forum.phalcon.io/discussion/1497/validation-with-presenceof-not-working

(4) https://docs.phalcon.io/en/latest/reference/models.html#disabling-enabling-features

This way Phalcon will not generate these user-unfriendly my_field is required messages. Instead of them I am adding PresenceOf validators to validation() method.

Both solutions seems to work. Thanks guys.



21.7k

@Conradaek, thank you for answer! Save a lot of my time – just faced that Model::validation() doesn't works and ORM sends data directly to database through my validations.

Can anyone state if using $this->setup() inside initialize() does apply to current model only? Looking at source code of Phalcon 4, setup() is a static method setting notNullValidations via globals_set()? So when disabling this option on a per model basis, wouldn't this apply to all models automatically?