使用Symfony2在一个Controller中处理两个表单

时间:2012-07-11 16:06:31

标签: symfony doctrine

嘿我在网站上用两种不同的语言保存每一页。我想管理我正在使用symfony2开发的管理区域的页面。

以下控制器代码能够在包含数据库中正确数据的同一页面上显示两个表单。管理DE语言的一种形式和EN的另一种形式:

查看:

<form action="{{ path('admin_about') }}" method="post" {{ form_enctype(formEN) }}>
            {{ form_widget(formEN) }}

            <button type="submit" class="btn btn btn-warning" naem="EN">Save</button>
        </form>

        <form action="{{ path('admin_about') }}" method="post" {{ form_enctype(formDE) }}>
            {{ form_widget(formDE) }}

            <button type="submit" class="btn btn btn-warning" name="DE">Save</button>
        </form>

控制器:     公共功能aboutAction(请求$ request)     {

    $pageEN = $this->getDoctrine()
    ->getRepository('MySitePublicBundle:Page')
    ->findOneBy(array('idName' => 'about', 'lang' => 'EN'));

    $pageDE = $this->getDoctrine()
    ->getRepository('MySitePublicBundle:Page')
    ->findOneBy(array('idName' => 'about', 'lang' => 'DE'));

    if (!$pageDE) {
        throw $this->createNotFoundException('About page (DE) not found.');
    }

    if (!$pageEN) {
        throw $this->createNotFoundException('About page (EN) not found.');
    }

    $formDE = $this->createFormBuilder($pageDE)
        ->add('title', 'text')
        ->add('content', 'text')
        ->getForm();

    $formEN = $this->createFormBuilder($pageEN)
        ->add('title', 'text')
        ->add('content', 'text')
        ->getForm();

    //Save Form here

    return $this->render('MySitePublicBundle:Admin:about.html.twig', array(
        'aboutPageDE' => $pageDE, 'aboutPageEN' => $pageEN, 'formDE' => $formDE->createView(), 'formEN' => $formEN->createView(),
    ));
}

我的问题是:如何保存已在一个控制器中使用的表单?

2 个答案:

答案 0 :(得分:2)

基于Symfony2文档的Forms and Doctrine部分(或者在您的情况下,因为您是not using a Form class) -

因此,假设您已设置//save form here以保存MySitePublicBundle:PageTitle(并且具有正常的getter / setter),Content处于if ($request->getMethod() == 'POST') { $form->bindRequest($request); // data is an array with "title" and "content" keys $data = $form->getData(); // You'll need to have some switch depending on which language you're dealing // with... (unless its both, then just repeat for $pageDE) $pageEn->setTitle($data['title']); $pageEn->setContent($data['content']); $em = $this->getDoctrine()->getEntityManager(); $em->persist($pageEn); $em->flush(); }

{{1}}

答案 1 :(得分:1)

在您的控制器中,您可以测试请求是否包含表单,例如:

if($this->getRequest()->get('form1')) {
    //
} elseif($this->getRequest()->get('form2')) {
    //
}