I am new with Symfony and FOSUserBundle, I have a relation One To One between User and Stream, when a user want to register he check if he is a streamer or not. If he is a streamer I want to create a new stream in relation with the user so here is the registerAction from FOSUserBundle that I'm overriding :
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
/*This is what I added*/
if($user->getIsStreamer()){
$em = $this->getDoctrine()->getManager();
$stream = new Stream();
$stream->setUser($user);
$em->persist($stream);
$em->flush();
}
/********/
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'fos_user_registration_confirmed';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
But nothing happened, what did I missed ?
You are missing the part that add the Stream to the user (and not only set the user of the stream).
First, be sure your association contains cascade={"persist"} to avoid need of manually persist the Stream :
/**
* @ORM\OneToOne(targetEntity="Stream", cascade={"persist"},
*/
protected $stream;
Then, change your setStream to make it calling $stream->setUser automatically :
public function setStream(Stream $stream = null)
{
$this->stream = $stream;
$stream->setUser($this); // Setter calling
return $this;
}
Now you can replace the logic of your condition like this :
if($user->getIsStreamer()){
$stream = new Stream();
$user->setStream($stream);
}
The association should be correctly stored when calling $em->flush at the end of your method.
In the case of FOSUB registration it should be :
$this->get('fos_user.user_manager')->updateUser($user);.
It's done in the confirmAction where your user is redirected in success.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With