如何使用symfony3.x正确显示多个CollectionType字段

时间:2017-08-17 17:51:32

标签: collections twig symfony3.x

您好我试图为使用多个不同集合的实体建模。我试用了https://github.com/ninsuo/symfony-collection项目,它提供了广泛的有用选项。我见过的最接近的例子是Collection of Collections,其中一个Entity有几个SAME子EntityType的集合。我试图用几个不同的子实体类型集合来实现相同的行为。

我面对我的实体的问题是,当我只放入一个集合时,代码工作正常,但当我添加另一个子实体的第二个集合并发送我的表单时,我的控制器代码最终删除了其他集合的元素。我把它缩小到了视野,因此我为什么要问这个特定的项目。

我目前正在使用Symfony 3.x,并且能够按照列出的示例一直到只使用一个集合,我能够添加,删除和更新。< / p>

我的控制器代码:

    <?php

    namespace SigavFileBundle\Form;

    use Ivory\CKEditorBundle\Form\Type\CKEditorType;
    use Symfony\Component\Form\Extension\Core\Type\TextType;
    use SigavFileBundle\Entity\BookingAccommodation;
    use SigavFileBundle\Entity\BookingIncludes;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\DateType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    use Symfony\Component\Form\Extension\Core\Type\MoneyType;
    use Symfony\Component\Form\Extension\Core\Type\IntegerType;
    use Doctrine\ORM\EntityRepository;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;

    class BookingType extends AbstractType
    {
        /**
        * {@inheritdoc}
        */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('flights', CollectionType::class, array(
                    'entry_type' => FlightDataType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__flights-collection__',
                    'attr'         => [
                        'class' => "flights-collection",
                    ],
                ))
                ->add('accommodations', CollectionType::class, array(
                    'entry_type' => BookingAccommodationType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__accomm-collection__',
                    'attr'         => [
                        'class' => "accomm-collection",
                    ],
                ))
                ->add('cars', CollectionType::class, array(
                    'entry_type' => BookingCarType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__cars-collection__',
                    'attr'         => [
                        'class' => "cars-collection",
                    ],
                ))
                ->add('transfers', CollectionType::class, array(
                    'entry_type' => BookingTransferType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__transfers-collection__',
                    'attr'         => [
                        'class' => "transfers-collection",
                    ],
                ))
                ->add('excursions', CollectionType::class, array(
                    'entry_type' => BookingExcursionType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__exc-collection__',
                    'attr'         => [
                        'class' => "exc-collection",
                    ],
                ))
                ->add('includes', CollectionType::class, array(
                    'entry_type' => BookingIncludesType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__inc-collection__',
                    'attr'         => [
                        'class' => "inc-collection",
                    ],
                ))
                ->add('customActivities', CollectionType::class, array(
                    'entry_type' => BookingCustomActivityType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__act-collection__',
                    'attr'         => [
                        'class' => "act-collection",
                    ],
                ))
                ->add('guides', CollectionType::class, array(
                    'entry_type' => BookingGuideType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__guides-collection__',
                    'attr'         => [
                        'class' => "guides-collection",
                    ],
                ))
                ->add('commentaries', CollectionType::class, array(
                    'entry_type' => BookingCommentariesType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'    => true,
                    'required'     => false,
                    'by_reference' => true,
                    'delete_empty' => true,
                    'prototype_name' => '__comm-collection__',
                    'attr'         => [
                        'class' => "comm-collection",
                    ],
                ))
            ;
        }

        /**
        * {@inheritdoc}
        */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'SigavFileBundle\Entity\Booking'
            ));
        }

        /**
        * {@inheritdoc}
        */
        public function getBlockPrefix()
        {
            return 'sigavfilebundle_booking';
        }


    }

如您所见,不同类型的多个集合。接下来,这是仅两个FormTypes的代码, BookingAccommodationType BookingCarType

BookingAccommodationType:

<?php

namespace SigavFileBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use SigavGeneralBundle\Controller\MealPlanController;
use SigavGeneralBundle\Entity\Hotel;
use SigavGeneralBundle\Entity\RoomType;
use SigavGeneralBundle\SigavGeneralBundle;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

class BookingAccommodationType extends AbstractType
{
    /**
    * {@inheritdoc}
    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ...
        // Attributes go here
        ...
    }

    /**
    * {@inheritdoc}
    */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SigavFileBundle\Entity\BookingAccommodation'
        ));
    }

    /**
    * {@inheritdoc}
    */
    public function getBlockPrefix()
    {
        return 'sigavfilebundle_bookingaccommodation';
    }


}

BookingCarType:

<?php

namespace SigavFileBundle\Form;

use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;

class BookingCarType extends AbstractType
{
    /**
    * {@inheritdoc}
    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ...
        // Attributes go here
        ...
    }

    /**
    * {@inheritdoc}
    */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SigavFileBundle\Entity\BookingCar'
        ));
    }

    /**
    * {@inheritdoc}
    */
    public function getBlockPrefix()
    {
        return 'sigavfilebundle_bookingcar';
    }


}

所有与视图相关的代码如下。

main_view.html.twig:

    <!-- A lot of HTML code before //-->
    {%
        form_theme form.accommodations
        'jquery.collection.html.twig'
        'booking/bookingAccommodations.html.twig'
    %}

    {{ form( form.accommodations) }}

    <!-- A lot of HTML code between //-->

    {%
    form_theme form.cars
    'jquery.collection.html.twig'
    'booking/bookingCars.html.twig'
    %}
    {{ form( form.cars) }}

    <!-- A lot of HTML code after //-->

    <script>
        function initCollectionHolders( $id, $form_id )
        {
            $($id).collection({
                name_prefix:  $form_id,
                add_at_the_end: true,
                allow_add: 1,
                allow_duplicate: 1,
                allow_remove: 1,
                duplicate: '<a href="#"><span class="pe-7s-copy"></span></a>',
                add: '<a href="#"><span class="pe-7s-plus"></span></a>',
                remove: '<a href="#"><span class="pe-7s-close-circle"></span></a>'
            });
        }

        initCollectionHolders('.accomm-collection', '{{ form.accommodations.vars.full_name }}');
        initCollectionHolders('.cars-collection', '{{ form.cars.vars.full_name }}');
    <script>

bookingCars.html.twig:

{% block sigavfilebundle_bookingcar_label %}{% endblock %}

{% block sigavfilebundle_bookingcar_widget %}

    {# HERE GOES THE ENTIRE FORM LAYOUT #} 

{% endblock %} 

bookingAccommodations.html.twig:

{% block sigavfilebundle_bookingaccommodation_label %}{% endblock %}

{% block sigavfilebundle_bookingaccommodation_widget %}

{# HERE GOES THE ENTIRE FORM LAYOUT #}

{% endblock %}

jquery.collection.html.twig:

{% block collection_widget %}
    {% spaceless %}
        {% if prototype is defined %}
            {% set attr = attr|merge({'data-prototype': form_row(prototype)}) %}
            {% set attr = attr|merge({'data-prototype-name': prototype.vars.name}) %}
        {% endif %}
        {% set attr = attr|merge({'data-allow-add': allow_add ? 1 : 0}) %}
        {% set attr = attr|merge({'data-allow-remove': allow_delete ? 1 : 0 }) %}
        {% set attr = attr|merge({'data-name-prefix': full_name}) %}
        {{ block('form_widget') }}
    {% endspaceless %}
{% endblock collection_widget %}

我首先想知道 symfony-collection 库是否可以在具有一个实体和多个不同子类型集合的环境中使用

提前致谢...

1 个答案:

答案 0 :(得分:0)

关注discussion on GitHub

name_prefix选项仅用于嵌套集合,它将有助于使用原型生成新条目,而不会在两个或更多集合之间发生冲突。

您要查找的是prefix选项,用于为symfony-collection插件生成的所有选择器添加前缀。在您的情况下,前缀对于所有集合都是相同的,因此单击一个或另一个按钮将触发对同一集合的操作。

如果您希望在同一页面上创建多个集合,则需要更改集合前缀,以便插件为正确的集合触发正确的操作。

例如:

 $('.collectionA').collection({
    'prefix': 'first-collection'
 });

 $('.collectionB').collection({
    'prefix': 'second-collection'
 });

然后,如果您想要在主题中编辑这些集合,您需要在添加按钮上首先通过first-collection-add替换collection-add。

<a href="#" class="first-collection-add btn btn-default">
    <span class="glyphicon glyphicon-plus-sign"></span>
</a>

有关正在运行的示例,请参阅this demo