【问题标题】:Processing Symfony Form in Embedded Controller在嵌入式控制器中处理 Symfony 表单
【发布时间】:2014-07-29 02:44:32
【问题描述】:

我正在尝试将控制器嵌入到这样的 Twig 模板中:

{{ render(controller('IRCGlobalBundle:MailingList:join')) }}

此控制器呈现一个基本表单以加入邮件列表:

namespace IRC\GlobalBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use IRC\GlobalBundle\Entity\MailingList;
use IRC\GlobalBundle\Form\Type\MailingListType;

class MailingListController extends BaseController
{
    public function joinAction(Request $request) {
        $this->getSiteFromRequest($request);
        $mailingList = new MailingList;
        $mailingList->setSite($this->site);
        $form = $this->createForm(new MailingListType(), $mailingList);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            echo "submitted form";
        } else {
            echo "unsubmitted form";
        }

        return $this->render('IRCGlobalBundle:Forms:join_mailing_list.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}

问题在于 $form->isSubmitted() 方法永远不会返回 true,因此无法验证/处理表单提交。我究竟做错了什么?我是否需要将表单的目标更改为指向我的嵌入式控制器?

【问题讨论】:

    标签: php forms symfony twig


    【解决方案1】:

    我猜这是因为表单将像这样呈现<form action="">,所以它会将信息发布到同一页面,但是由于您使用子请求呈现表单,因此新的子请求不会携带任何表单数据.

    解决此问题的最简单方法是破解表单操作属性并将请求发送到joinAction,您可以在处理表单后将请求redirectforward发送到用户所在的页面从。

    这样的事情应该可以工作:

    $form = $this->createForm(new MailingListType(), $mailingList, array(
         'action'   => //generate a url to joinAction
    ));
    

    【讨论】:

    • 由于joinAction没有Routing,如何生成url?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多