簡體   English   中英

嵌套的CollectionType

[英]Nested CollectionTypes

我有一個旅館酒店,其中包含一些CollectionType,又包含一些CollectionType。 以這種形式,我想添加一個父實體,該實體可以包含多個子實體,而子實體又可以包含幾個實體:

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

這里的實體關系:

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;

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

而且我有一個處理字段的JS文件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);
                });
            })
        }
    });
});

該事件有效,當我單擊“添加元素”時,將正確的FormType追加到正確的div中。 但是,當我提交數據時,諸如PictureRoom或PriceRoom之類的孫子字段不會保留到數據庫中。 有人知道如何使用這種嵌套的CollectionType表單嗎?

非常感謝你的幫助。

重要的是要了解,CollectionType是Symfony Form Component的功能,並且不需要太多教義。

因此,使用CollectionType,您將在Form Data ArrayCollection中包含一些對象,但是如何處理和持久化它們-這完全是您的責任。

就個人而言,我更喜歡使用empty_data屬性來保留通過CollectionType創建的新實體。

有點像

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

RoomPicture相同。 而且您必須在任何級別上都具有cascade={"remove", "persist"} (要保留給酒店的房間)。

在這種情況下,不確定$form->getParent()->getData()是否具有Room實體,但是無論如何,都可以通過$form對象訪問它,只需玩一點代碼即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM