Symfony2复杂形式的最佳实践

时间:2015-12-02 10:47:15

标签: php forms symfony handle

我的Symfony2应用程序中有一个复杂的数据库模式,其中有许多实体相互链接。

因此,我的表格也很复杂:我可以有很多链接表格;例如,“Cinema”可以有一个地址,但也可以链接到几个“电影”(带有一个添加新电影的按钮)。

使用基本的Symfony2表单类型来处理这个问题非常困难; 我更喜欢在Twig视图中手动创建自己的表单;使用一堆Javascript。

但我不知道如何处理表单提交?

  • 我应该定义CinemaType并仅使用它来处理表单请求(但不能用于创建表单视图)?
  • 我应该在我的控制器中使用createFormBuilder()来定义基本表单字段并使用handleRequest()方法进行检查吗?
  • 或者,最后,应该获取所有_POST数据并手动检查

谢谢:)

2 个答案:

答案 0 :(得分: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

如果你擅长人体工程学,你可以创建漂亮的形式,分成多个标签或任何其他可想象的设计......

答案 1 :(得分:0)

您始终可以创建自己的简单表单类,该类实现与Symfony2相同的方法:

  • 的handleRequest
  • 验证
  • CreateView的

等等。