Reputation: 2691
I'm making a website where users can create albums.
I would like to create a default album per user.
I would like to create an Album entity and to persist it in the constructor of my User class.
Is it possible ? I just know that the entityManager is not accessible from an Entity... That's why it's a problem for me.
Upvotes: 0
Views: 520
Reputation: 9246
Even though this technically IS possible I would strongly recommend you not to do this.
To answer your question, it is possible and it would be done like this:
class User extends FOSUser
{
/**
* @ORM\OneToMany(targetEntity="Album", cascade={"persist"})
*/
private $albums;
public function __construct()
{
$this->albums = new ArrayCollection();
$this->addAlbum(new Album());
}
public function addAlbum(Album $album)
{
$this->albums[] = $album;
}
public function getAlbums()
{
return $this->albums:
}
}
With setup like this whenever you create a new user and save it, a related album will be created together with it. I have to repeat, even though it's possible, don't do it like this.
There are few strategies that can be used to achieve what you want.
If you're not using 1.3.x version of FOSUserBundle but master, you can see that RegistrationController fires a few events. The one you're interested in is FOSUserEvents::REGISTRATION_INITIALIZE
. You should create an event listener and add album to user in your listener.
If you're using one of older versions, these events don't exist unfortunately and you can do it two ways.
createUser
method. You can add your album adding logic there. I would prefer this approach.Upvotes: 2