Skip to content
Advertisement

Symfony, constraint for User

Good day! Just started learning Symfony on my own.

I’m making a news portal. The administrator can download news from an Excel file. I am converting a file to an associative array. For example:

JavaScript

Next, I want to send this array to the form and use ‘constraints’ to validate it. There are no problems with the fields ‘Title’, ‘Text’, ‘Image’. I don’t know how to properly check the ‘User’ field. The user in the file is submitting an Email, but I want to check that a user with that Email exists in the database.

NewsImportType

JavaScript

The entities User and News are connected by a One-to-Many relationship.

I was thinking about using ChoiceType and calling UserRepository somehow, but I don’t understand how to apply it correctly.

Please tell me how to correctly write ‘constraint’ for the ‘user’ field. thank!

Advertisement

Answer

Create a Custom Constraint. This way it is reusable in any other form you would like to check for a user.

Create a new folder in your project src/Validator then put these 2 files in there.

The Constraint

JavaScript

The Validator

JavaScript

In your form you can now use the validator

JavaScript

Remember to add use AppValidatorUserAccountExists; to your form.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement