Symfony 2 - 单独的表单逻辑,重定向后显示表单错误 [英] Symfony 2 - separate form logic, show form errors after redirect

查看:25
本文介绍了Symfony 2 - 单独的表单逻辑,重定向后显示表单错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分离表单验证逻辑:

I want to separate form validation logic:

public function contactAction()
{
    $form = $this->createForm(new ContactType());

    $request = $this->get('request');
    if ($request->isMethod('POST')) {
        $form->submit($request);
        if ($form->isValid()) {
            $mailer = $this->get('mailer');
            // .. setup a message and send it

            return $this->redirect($this->generateUrl('_demo'));
        }
    }

    return array('form' => $form->createView());
}

我想转化为 2 个独立的操作:

I want to translate into 2 separate actions:

public function contactAction()
{
    $form = $this->createForm(new ContactType());
    return array('form' => $form->createView());
}

public function contactSendAction()
{
    $form = $this->createForm(new ContactType());
    $request = $this->get('request');
    if ($request->isMethod('POST')) {
        $form->submit($request);
        if ($form->isValid()) {
            $mailer = $this->get('mailer');
            // .. setup a message and send it using 

            return $this->redirect($this->generateUrl('_demo'));
        }
    }
    // errors found - go back
    return $this->redirect($this->generateUrl('contact'));
}

问题是,当表单中存在错误时 - 在表单验证和重定向之后,contactAction 中不显示.(可能它们在重定向后已经被遗忘 - 错误上下文将丢失)

The problem is that when errors exist in the form - after form validation and redirect the do NOT showed in the contactAction. (probably they already will be forgotten after redirection - errors context will be lost)

推荐答案

如果你查看了 CRUD 生成器 处理此问题,您将看到失败的表单验证不会返回重定向,而是使用与 GET 方法相同的视图.因此,在您的示例中,您只需:

If you check out how the code generated by the CRUD generator handles this you will see that a failed form validation does not return a redirect but instead uses the same view as the GET method. So in your example you would just:

return $this->render("YourBundle:Contact:contact.html.twig", array('form' => $form->createView()))

而不是返回重定向.这意味着您不会像在重定向中那样丢失表单错误.CRUD 生成器添加的其他内容是 方法要求,这意味着您可以指定 ContactSendAction 需要 POST 方法,因此不需要额外的 if($request->isMethod('POST')){声明.

rather than return the redirect. This means you do not lose the form errors as you do in a redirect. Something else the CRUD generator adds is the Method requirement which means you could specify that the ContactSendAction requires the POST method and thus not need the extra if($request->isMethod('POST')){ statement.

如果你在别处指定模板,你也可以只返回一个数组,例如你可以使用 @Template 注释 然后只是

You can also just return an array if you specify the template elsewhere, for example you could use the @Template annotation and then just

return array('form' => $form->createView())

这篇关于Symfony 2 - 单独的表单逻辑,重定向后显示表单错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆