Using Enum in a Symfony App isn’t obvious. If your Enum is short, you can directly put it on your
entity. But if it grows, it will be quickly unmanageable.
The problem
Ok given, you want to create a message object which contains an attribute called type. Like
Twitter Bootstrap’s Alert, your Message type’s
attribute must contain some specific strings (e.g. info, success…).
In the
official documentation,
Doctrine provides 2 solutions for MySQL Database. What happens if we want to use another Database
like PostgreSQL? By the way, you can also take a look at these solutions. As far as I am concerned,
I don’t like them because it didn’t solve the problem on the PHP side.
Obviously, we can also create a Table called MessageType. But according to me, a database table must
be used to store data. In this case, a type isn’t managed by a human.
So we need custom reusable PHP Enum.
Let’s do this!
A solution
First, you need to create a MessageTypeEnum.
Here is an example of use:
Now, you need to adapt your Entity:
And this is the form: (MessageType.php)
And tadaaa it works!
Your Form should look like this:
About the author
Hey, I'm Maxence Poutord, a passionate software engineer. In my
day-to-day job, I'm working as a senior front-end engineer at Orderfox.
When I'm not working, you can find me travelling the world or cooking.