phpsymfonyconstraints

Managing the case sensitivity for a unique field in symfony


I have a form where there is one field "place" and I have used UniqueEntity to make that field unique. But the issue I'm currently facing is that if the user types the same place but changes just the case of their input the form will submit and add the new input in the db. This is not what I want it should display an error message that this place is already being used and they need to type different one regardless if its in upper or lower case.

i have tried making my own custom contraint but it didnt work.


Solution

  • You can keep your unique constraint but use the parameter "repositoryMethod" to use your own query that would be case insensitive.

    From the UniqueEntity documentation:

    The name of the repository method used to determine the uniqueness. If it's left blank, findBy() will be used. The method receives as its argument a fieldName => value associative array (where fieldName is each of the fields configured in the fields option). The method should return a countable PHP variable.

    So create a custom method in your repository that search with a UPPER or LOWER function on your field and use it in your constraint:

    #[UniqueEntity(fields: ['place'], repositoryMethod: 'caseInsensitiveFindBy')]