0

嘿,我在我的网站上以两种不同的语言保存每一页。我想用我目前正在使用 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 $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(),
    ));
}

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

4

2 回答 2

2

基于 Symfony2 Docs 的Forms and Doctrine部分(或者在您的情况下,因为您没有使用 Form 类)-

所以你//save form here假设你已经设置MySitePublicBundle:Page保存Titleand Content(并且有正常的getter/setter)。

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();
}
于 2012-07-11T22:15:04.213 回答
1

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

if($this->getRequest()->get('form1')) {
    //
} elseif($this->getRequest()->get('form2')) {
    //
}
于 2012-07-11T16:18:47.583 回答