我在控制器中有以下代码:
$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()
));
有没有办法在数据库中以电子邮件地址未知的形式抛出错误,而不是创建新操作?
或者我在文档中遗漏了什么?
答案 0 :(得分:1)
如果你想 抛出错误 ,那么要么首先捕获它,要么捕获所有异常并重新抛出你想要的那个
如果您想在表单中添加错误,可以创建FormError并将其添加到表单中:
use Symfony\Component\Form\FormError;
...
catch (\Doctrine\Orm\NoResultException $e) {
$form->addError(new FormError('the e-mail was not found'));
}
答案 1 :(得分: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();