Symfony2复杂形式的最佳实践

I have a complex database schema in my Symfony2 application, with a lot of entities linked to each others.

Consequently, my forms are also complicated : I can have many linked forms ; for example a "Cinema" can have an Address, but can also be linked to several "Movies" (with a button to add a new movie).

It's very very difficult to handle this using basic Symfony2 form Types ; I prefer to create my own form manually in a Twig view ; using a bunch of Javascript.

But I don't know how to handle the form submission ?

  • Should I define a CinemaType and use it only to handle the form request (but not for creating the form view) ?
  • Should I use a createFormBuilder() in my Controller to define the basic form fields and check them with the handleRequest() method ?
  • Or, finally, should get all my _POST data and check them manually ?

Thanks :)

You can always create your own simple form class that implements the same methods as the Symfony2 ones:

  • handleRequest
  • validate
  • createView

And so on.

I don't understand very well the problem...


You can play with your multiple nested form and the whole structure (html + js) is in the doc: http://symfony.com/doc/current/cookbook/form/form_collections.html

The official doc gives too a jsfiddle : http://jsfiddle.net/847Kf/4/

Just an extract for the answer validation :

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

You can customize the rendering, or/and creating your own theme : http://symfony.com/doc/current/cookbook/form/form_customization.html


You can handle the form validation : http://symfony.com/doc/current/book/validation.html


And if you are good at ergonomics, you can create pretty form splited in multiple tabs or with any other thinkable design...