2015-12-02 118 views
-6

我的Symfony2應用程序中有一個複雜的數據庫模式,其中有很多實體相互鏈接。Symfony2複雜表單的最佳實踐

因此,我的表單也很複雜:我可以有很多鏈接表單;例如「電影」可以有一個地址,但也可以鏈接到幾個「電影」(用一個按鈕來添加一部新電影)。

使用基本的Symfony2表單類型來處理這個問題非常困難; 我更喜歡在Twig視圖中手動創建我自己的窗體;使用一堆Javascript。

但我不知道如何處理表單提交?

  • 我應該定義一個CinemaType並僅用它來處理表單請求(但不能用於創建表單視圖)嗎?
  • 我應該在我的控制器中使用createFormBuilder()來定義基本表單字段並使用handleRequest()方法檢查它們嗎?
  • 或者,最後,應該得到我所有的_POST數據,並手動檢查它們

謝謝:)

+0

你看過表單集合嗎? http://symfony.com/doc/2.8/cookbook/form/form_collections.html。在您的問題描述中看不到任何看起來很難的內容。我同意小枝可以阻擋。我實現了我自己的form twig擴展來獲得對html輸出的更多控制。但是這些表單在聚合根對象和html表單元素之間做了很好的映射。 – Cerad

回答

0

你總是可以創建一個實現同樣的方法,將那些Symfony2的自己的簡單表單類:

  • 的handleRequest
  • 驗證
  • CreateView的

依此類推。

+0

是不是''綁定''有利於'handleRequest'?在新版本(2.7和2.8分支)中,我看不到「綁定」了。 – cezar

+0

確實,正在尋找一箇舊項目。 – COil

1

我也不是很明白的問題...


您可以使用多個嵌套形式和整個結構發揮(HTML + JS)是在doc: http://symfony.com/doc/current/cookbook/form/form_collections.html

官方文檔也提供了一個的jsfiddle:http://jsfiddle.net/847Kf/4/

的回答驗證只是摘錄:

function addTagForm($collectionHolder, $newLinkLi) { 
    // Get the data-prototype explained earlier 
    var prototype = $collectionHolder.data('prototype'); 

    // get the new index 
    var index = $collectionHolder.data('index'); 

    // Replace '$$name$$' in the prototype's HTML to 
    // instead be a number based on how many items we have 
    var newForm = prototype.replace(/__name__/g, index); 

    // increase the index with one for the next item 
    $collectionHolder.data('index', index + 1); 

    // Display the form in the page in an li, before the "Add a tag" link li 
    var $newFormLi = $('<li></li>').append(newForm); 

    // also add a remove button, just for this example 
    $newFormLi.append('<a href="#" class="remove-tag">x</a>'); 

    $newLinkLi.before($newFormLi); 

    // handle the removal, just for this example 
    $('.remove-tag').click(function(e) { 
     e.preventDefault(); 

     $(this).parent().remove(); 

     return false; 
    }); 
} 

您可以自定義渲染,或/和創建自己的主題: http://symfony.com/doc/current/cookbook/form/form_customization.html


您可以處理表單驗證http://symfony.com/doc/current/book/validation.html


如果你擅長人體工程學,你可以創建漂亮的窗體在多個選項卡或任何其他可想象的設計分裂...