Skip to content
Advertisement

Default value of Doctrine ORM association

I have the entity (such as below). I want to set some default values while creating. As you can see in __construct, it is easy to set the $name (string), but how can I set the $group? (for example I know that there is a group in database with id=122)

JavaScript

Advertisement

Answer

I agree with moonwave99 that this is poor design. Here you are trying to access the database (through the Doctrine service) from a place that is not container-aware (i.e. it does not, and should not, know about Doctrine).

I had a similar issue recently… pretty much the same exact issue, actually. But I didn’t want this logic to be inside the controller. So I wrote a service to take care of the User creation. And I gave that service access to the only other service it needed: Doctrine.

Here’s an example, where a User is created with all available Roles:

JavaScript

Now register that service in config.yml or services.yml, remembering to pass the Doctrine service to it:

JavaScript

And that’s it… Now, in your controller, you can create a new User by doing:

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