Search code examples
formssymfonyfosuserbundledatabase-relations

FOSUserBundle - persisting related entities/documents


I have an app where each User has a "Home".

I have overridden my FOSUserBundle registration FormType to embed the Home and capture some properties in the registration process. Unfortunately when I register, the new User is persisted but the new Home is not.

I don't really want a postPersist listener set on the User in-case I want to create a second User for an existing Home. I assume I have to override the RegistrationFormHandler onSuccess() or process() methods and manually persist the home? If this is the case, do I have to inject the DocumentManager in the constructor? Is this the best way to do it?

I'm using Doctrine MongoDB ODM as the storage layer if that makes any difference?


Solution

  • I created my own RegistrationFormHandler and overrode the onSuccess method:

    public function onSuccess(UserInterface $user, $confirmation)
    {
        $home = $user->getHome();
        $this->documentManager->persist($home);
        $this->documentManager->flush();
    
        parent::onSuccess($user, $confirmation);
    }
    

    This uses the document manager which you'll need to inject in the constructor.