2017-05-18 19 views
2

我有2個實體:郵政。在我的TestController我有一個函數名爲:addAction()其中即時試圖讓這兩個實體,並添加他們的一些數據,但當我試圖做到這一點時,我運行我的應用程序,窗體成功submited ,但2個表格(帖子和文章)是空的。爲什麼?如何在Symfony的1根小枝中使用2種形式?

這裏是我的addAction功能:

public function addAction(Request $request) 
    { 
     $post = new Post(); 
     $article = new Article(); 

     $postForm = $this->createForm(PostType::class, $post); 
     $articleForm = $this->createForm(ArticleType::class, $article); 

     $postForm->handleRequest($request); 
     $articleForm->handleRequest($request); 

     if ($postForm->isValid() && $articleForm->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 

      $em->persist($post); 
      $em->persist($article); 

      $em->flush(); 
     } 
     return $this->render('add/add.html.twig', array(
      'postForm' => $postForm->createView(), 
      'articleForm' => $articleForm->createView() 
     )); 
    } 

而且樹枝:

{% extends 'base.html.twig' %} 

{% block body %} 
    <div style="text-align: center;"> 
     <div class="container"> 
      <h1>Add Post</h1> 
      {{ form_start(postForm) }} 
       {{ form_widget(postForm) }} 
       <button class="btn btn-primary" type="submit">Add Post <span class="glyphicon glyphicon-plus"></span></button> 
      {{ form_end(postForm) }} 
     </div> 
    </div> 
    <hr> 
    <div style="text-align: center;"> 
     <div class="container"> 
      <h1>Add Article</h1> 
      {{ form_start(articleForm) }} 
      {{ form_widget(articleForm) }} 
      <button class="btn btn-primary" type="submit">Add Article <span class="glyphicon glyphicon-plus"></span></button> 
      {{ form_end(articleForm) }} 
     </div> 
    </div> 
{% endblock %} 
+1

我看到的第一個問題是,提交一個表單的頁面上有2個表單將導致發送數據只爲該submited形式 - 不是兩個。 – adelineu

+0

問題如何解決? –

+0

嘗試查看是否可以爲兩個實體創建一個表單。我不知道handleRequest()的結果,如果你打算在一個表單中使用它們中的兩個(如果它知道如何分配字段到實體)。 – adelineu

回答

4

不能同時提交兩種形式。所以,相反,他們一個接一個地提交

$postForm->handleRequest($request); 
if ($postForm->isSubmitted() && $postForm->isValid()) { 
    // persist and flush $post 
} 

$articleForm->handleRequest($request); 
if ($articleForm->isSubmitted() && $articleForm->isValid()) { 
    // persist and flush $article 
}