phpsymfonysilexsymfony-2.4php-closures

Validate field based on another field using additional database


I have a simple form, which contains two fields, the first field is just a select and the second field contains a value, which needs to be checked with the help of the first field.

I have found a similar question Symfony2 form validation based on two fields and tried to use the Callback validator.
I have read the documentation, but I can't figure out how I can use it with access to the database.

It seems that the only way is to call the validation method statically, but in this case I loose the context of my controller. I need it to access for example the database.
In this relation I am using Silex and want to access services provided by it.

The form isn't mapped to any class, so the creation of an own constraint looks wrong for me, because I don't see any way to pass the other fields to the validator.

Is there any way to achieve it?

Or do I need another approach?


Solution

  • I strongly advise you to map the form to a class and create a custom constraint...

    I have written a detailed example on how to:

    TLDR:

    What you need is a custom validator on class level.

    A class-level validator is needed because you need to access the whole object (not only a single property) if you want validate multiple related values...

    ... or need to fetch something from database using another property as select-criteria.

    Here's the the complete answer with example.


    Another option could be creating a form-event listener and passing the object-manager to it before adding it to the form.

    Then take care of the validation-process (checking the data against the database + eventually adding errors to the form) inside the listener yourself.