How to check unique entity in the controller

184 views Asked by At

Before persisting my entity I would like to check if it doesn't already exist according to three fields. I know how to use the annotation "UniqueEntity" but it doesn't work for me because I can't use a conventional "formType". To summarise, my question is: In symfony 2 what's the best way to perform a unique entity check in the controller?

I already thought about get an array of Id then use an "in_array" function to decide to persist my entity or not. But I'm not sure about the efficiency of that method.

I expect that entities that already exists in my database (according to 3 fields) are not persisted.

Thank you for your answers.

1

There are 1 answers

0
Bertrand On

It's not a very good approach but if you can't use UniqueEntity, you can execute a findBy on your repository and decide to persist your entity or not.

$entityExists = $em->getRepository('MyBundle:MyEntity')->findBy(array('field1' => $value1,'field2' => $value2,'field3' => $value3));