1

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?

Community
  • 1
  • 1
CSchulz
  • 10,882
  • 11
  • 60
  • 114

1 Answers1

2

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:

  • create your own validation constraint
  • turn it into a service
  • inject the object-manager
  • access the database from the constraint

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.

Community
  • 1
  • 1
Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130
  • Sounds very good, thanks for the advice and the link. One question about your answer, the first version had something about classes on the fly. Can you give me more information in that direction? My form isn't really related to a class. – CSchulz Feb 24 '14 at 23:27
  • I removed that because creating a class, setting the form-data, adding validation-classmetadata and afterwards passing it to the validator service ... is basically what mapping to a form does. Don't re-invent the wheel. Even if the form-data isn't really related to another class ... just do it the OOP-way and create a class for it. It isn't worth the effort - but if you'd like to play around and get used to symfony's components better... you can puzzle together all that stuff yourself ! :) – Nicolai Fröhlich Feb 24 '14 at 23:38