简体   繁体   中英

Nested CollectionTypes

I have a form Hotel , which contain some CollectionType , which again contain some CollectionType . In this form , I want to add a parent entity , which can contain multiple children, which may again contain several entities :

class HotelType extends AbstractType{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('rooms', CollectionType::class, array(
            'entry_type' => RoomType::class,
            "label" => "Add rooms",
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
        ))

class RoomType extends AbstractType{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options){
    $builder

        ->add('pictures', CollectionType::class, array(
            'entry_type' => PictureRoomType::class,
            "label" => "Add pictures",
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
        ))
        ->add('prices', CollectionType::class, array(
            'entry_type' => PriceRoomType::class,
            "label" => "Add prices",
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
        ))
    ;

Here the entities relation :

class Room {
/**
 * @ORM\ManyToOne(targetEntity = "Hotel", inversedBy = "rooms")
 * @ORM\JoinColumn(name = "id_hotel", referencedColumnName = "id")
 */
private $hotel;

/**
 * @ORM\OneToMany(targetEntity="PictureRoom", mappedBy="room", cascade={"remove", "persist"})
 */
private $pictures;
/**
 * @ORM\OneToMany(targetEntity="PriceRoom", mappedBy="room", cascade={"remove", "persist"})
 */
private $prices;

class Hotel {
/**
 * @ORM\OneToMany(targetEntity="Room", mappedBy="hotel", cascade={"remove", "persist"})
 */
private $rooms;

The HotelController :

class HotelController extends Controller{
/**
 * Creates a new Hotel entity.
 *
 * @Route("/new", name="hotel_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $hotel = new Hotel();
    $form = $this->createForm('AppBundle\Form\HotelType', $hotel);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        if ($hotel->getRooms() != null) {
            foreach ($hotel->getRooms() as $room) {
                if (!empty($room)) {
                    $room->setHotel($hotel);
                    if ($room->getPictures() != null) {
                        foreach ($room->getPictures() as $picture) {
                            if (!empty($picture)) {
                                $picture->setRoom($room);
                                $picture->upload();
                            }
                        }
                    }
                    if ($room->getPrices() != null) {
                        foreach ($room->getPrices() as $price) {
                            if (!empty($price)) {
                                $price->setRoom($room);
                                $price->setIdTva($price->getIdTva()->getId());
                            }
                        }
                    }
                    $room->setIdTva($room->getIdTva()->getTva());
                }
            }
        }

And i've a JS file that handle the fields append :

$(document).ready(function () {

var fields = $('div[data-prototype]');
var childElementCount = 1;

fields.each(function (index) {
    var field = $(this);
    var elementCount = 1;

    field.parent().append('<a href="#" class="btn btn-primary" id="add-another-' + index + '"><i class="glyphicon glyphicon-plus"></i> Add an element</a>');

    var trigger = $("#add-another-" + index);
    var childCollections;

    trigger.click(function (e) {
        var newWidget = field.attr('data-prototype');
        newWidget = newWidget.replace(/label__/g, "");
        newWidget = newWidget.replace(/col-md-6/g, "col-md-12");
        newWidget = newWidget.replace(/__name__/g, elementCount);
        e.preventDefault();
        elementCount++;
        field.parent().append(newWidget);

        childCollections = field.parent().find('.collection');

        if(childCollections.length == 1){

            childCollections.parent().append('<a href="#" class="btn btn-primary" id="add-another-' + index + '-'+ elementCount + '"><i class="glyphicon glyphicon-plus"></i> Add an element</a>');
            var childTrigger = $('#add-another-' + index + '-' + elementCount);

            childTrigger.click(function (e) {
                var newChildWidget = childCollections.find('div[data-prototype]').attr('data-prototype');
                //newChildWidget = newChildWidget.replace(/__child__/g, "_" + childElementCount);
                console.log(newChildWidget);
                e.preventDefault();
                childElementCount += 1;
                console.log(childElementCount);
                childCollections.parent().append(newChildWidget);
            });

        } else if (childCollections.length > 1) {
            childCollections.each(function(childIndex){
                var childField = $(this);
                childField.parent().append('<a href="#" class="btn btn-primary" id="add-another-' + index + '-'+ elementCount + childIndex + '"><i class="glyphicon glyphicon-plus"></i> Add an element</a>');
                var childTrigger = $('#add-another-' + index + '-' + elementCount + childIndex);


                childTrigger.click(function (e) {
                    var newChildWidget = childField.find('div[data-prototype]').attr('data-prototype');
                    //newChildWidget = newChildWidget.replace(/__child__/g, "_" + childElementCount);
                    console.log(newChildWidget);

                    e.preventDefault();
                    childElementCount+= 1;
                    console.log(childElementCount);
                    childField.parent().append(newChildWidget);
                });
            })
        }
    });
});

The event works, when i click on "Add an element", the correct FormType append in the correct div. But when i submit the data, the grandchilds fields, like PictureRoom or PricesRoom are not persisted to the database. Does someone know how to work with that kind of nested CollectionType forms ?

Thanks a lot for your help.

It's important to understand, that CollectionType is a feature of Symfony Form Component, and it doesn't really a lot to have to doctrine.

So with CollectionType you will have in your Form Data ArrayCollection of some objects, but how to process and persist them - it's totally your responsibility.

Personally, I prefer to use empty_data property to persist new entities created through CollectionType.

Something's like

   ->add('prices', CollectionType::class, array(
        'entry_type' => PriceRoomType::class,
        "label" => "Add prices",
        'allow_add' => true,
        'allow_delete' => true,
        'prototype' => true,
        'empty_data' => function (FormInterface $form) {
             $price = PriceRoom();
             $price->setRoom($form->getParent()->getData());
             return $price; 
         },
    ))

Same for Room and Picture . And you have to have cascade={"remove", "persist"} on any level (Rooms to be persisted for Hotel).

Not sure in this case if $form->getParent()->getData() will have Room entity, but anyway it could be somehow accessed from $form object, just play a bit with a code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM