问题
HI in my case embedded forms validation doesn't work.
And i have set 'cascade_validation' => true,
even tried with Valid constraint in my model to force validation on a child object. Also doesn't work.
Here how it looks like:
My User class:
/**
* @ORM\OneToOne(targetEntity="Info", inversedBy="user", cascade={"persist"})
* @Assert\Valid
*/
protected $info;
As we see it contain an extra info field type.
And now my overwritten controller:
public function registerBrandAction(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(new RegistrationFormType($user));
$form->setData($user);
$form->add('info', new InfoFormType());
$brand = new Info();
$user->setBrand($info);
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$em = $this->container->get('doctrine')->getManager();
$em->persist($info);
$user->addRole('ROLE_ADMIN');
$userManager->updateUser($user, false);
$em->flush();
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:registerAdmin.html.' . $this->getEngine(), array(
'form' => $form->createView(),
));
}
So in my RegistrationFormType i have enabled cascade_validation. But Validations still doesn't work. Can anyone help me ? And also why am i adding this in controller ? Becous i have to 2 of users and i dont want to form have that Info for other one.
回答1:
easy as that! just add to your validations fos user registration form group
* @Assert\NotBlank(groups={"registration"})
and to your form:
'validation_groups' => array('registration'),
and it works!
来源:https://stackoverflow.com/questions/23896211/symfony2-embedded-forms-validation-for-fosuserbundle