I've a registration form, which needs a checkbox for agreeing to the terms and conditions of the website. Since I dont want to save the value of the checkbox inside the user object, i've manually added a checkbox field which is not mapped to the data object.
When I submit the registration form without ticking the Terms checkbox, an error is displayed (Thats okay, since the checkbox is required). However the checkbox is now checked, which is unwanted. It should either be always unchecked (so that after every mistake in the form you have to check it again) or stay the way you've submitted it.
Below is the code (overwritten RegistrationController from the FOSUserBundle):
public function registerAction(Request $request)
{
/** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->container->get('fos_user.registration.form.factory');
/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->add('xterms', 'checkbox', array(
'mapped' => false,
'empty_data' => false,
'required' => 'required',
'label' => 'label.terms',
'constraints' => array(new NotNull())));
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}