2017-05-18 9 views
2

Imには2つのエンティティ:ポストがあります。私のTestController私はこれらの2つのエンティティを取得し、いくつかのデータを追加しようとしていますaddAction()という名前の関数がありますが、私は私のアプリケーションを実行するときにしようとしているとき、フォームは、 2つのテーブル(記事と記事)は空です。どうして ?あなたは、同時に2つのフォームを送信することはできませんSymfonyで1つの枝に2つのフォームを使用するには?

{% 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つの形態を保持しているページ上の一つの形をsubmitingするだけでsubmitedフォームのデータを送信する結果となるということです。 – adelineu

+0

どのように問題を解決できますか? –

+0

両方のエンティティに対して1つのフォームを作成できるかどうかを確認してください。エンティティにフィールドを割り当てる方法がわかっている場合、2つのフォームを1つのフォームで使用する場合は、handleRequest()の結果を実際にはわかりません。 – adelineu

答えて

4

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() 
     )); 
    } 

そして小枝:

は、ここに私のaddAction機能です。両方ではないために - だから、代わりに、私は見それらを1

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

$articleForm->handleRequest($request); 
if ($articleForm->isSubmitted() && $articleForm->isValid()) { 
    // persist and flush $article 
} 
関連する問題