0

我在控制器中有以下代码:

$form = $this->createFormBuilder()
                ->add('email', 'email', array(
                    'constraints' => array(new MaxLength(array('limit' => 255, 'message' => 'email.maxlength'))),
                    'required' => true,
                    'attr' => array('oninvalid' => "setCustomValidity('" . $this->get('translator')->trans('email.oninvalid', array(), 'validators') . "')",
                        'placeholder' => $this->get('translator')->trans('email.placeholder', array(), 'validators'),)
                ))
                ->getForm();
if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        $formData = $form->getData();

        if ($form->isValid()) {
        $formData->getEmail();
                $em = $this->getDoctrine()->getManager();
                $rep = $em->getRepository('FrontendAccountBundle:User');
                $q = $rep->createQueryBuilder('u')
                        ->join('u.state', 's')
                        ->where('u.email = :email')
                        ->andWhere('s.id = :sid')
                        ->setParameters(array('email' => $email))
                        ->getQuery();

                try {
                    $user = $q->getSingleResult();
                } catch (\Doctrine\Orm\NoResultException $e) {
                    //return $this->redirect($this->generateUrl('frontend_account_unknown_email'));
                }
} 
return $this->render('FrontendAccountBundle::send_new_activation_link.html.php', array(
                'form' => $form->createView()
            ));

有没有办法以数据库中未知电子邮件地址的形式抛出错误,而不是创建新操作?

还是我错过了文档中的某些内容?

4

2 回答 2

1

如果你想抛出一个错误,那么要么一开始就不要捕获它,要么捕获所有异常并只重新抛出你想要的异常。

如果要向表单添加错误,可以创建一个FormError并将其添加到表单中:

use Symfony\Component\Form\FormError;

...

catch (\Doctrine\Orm\NoResultException $e) {
    $form->addError(new FormError('the e-mail was not found'));
}
于 2013-01-29T21:00:33.153 回答
0

对于那些想要查看完整代码的人。

$form->addError(new FormError('the e-mail was not found'));

$templating = $this->container->get('templating');

$response = new Response($templating->render('FrontendAccountBundle::send_new_activation_link.html.php', array(
                         'form' => $form->createView()
                         )));
$response->send();
于 2013-01-30T15:07:26.777 回答