首页 > 解决方案 > 创建一个以 CollectionType 为父的自定义字段类型

问题描述

我有一个SmsType,EmailType并且VoiceCallType全部包含以下集合:

            ->add('answers', CollectionType::class, [
                'label'         => 'form.communication.fields.answers',
                'entry_type'    => AnswerType::class,
                'entry_options' => [
                    'label' => false,
                ],
                'allow_add'     => true,
                'allow_delete'  => true,
                'delete_empty'  => true,
                'prototype'     => true,
                'required'      => false,
                'attr'          => [
                    'class' => 'collection',
                ],
            ])

为了简化,我创建了一个AnswersType作为CollectionType父对象:

<?php

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AnswersType extends AbstractType
{
    public function setDefaultOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'label'         => 'form.communication.fields.answers',
            'entry_type'    => AnswerType::class,
            'entry_options' => [
                'label' => false,
            ],
            'allow_add'     => true,
            'allow_delete'  => true,
            'delete_empty'  => true,
            'prototype'     => true,
            'required'      => false,
            'attr'          => [
                'class' => 'collection',
            ],
        ]);
    }

    public function getParent()
    {
        return CollectionType::class;
    }
}

->add('answers', AnswersType::class)在每种表单类型上使用,而不是在大块上使用。


由于某种原因,生成的标记并不相同:

没有AnswersType,会form_row()生成以下标记:

<fieldset class="form-group"><div id="campaign_trigger_answers" class="collection" data-prototype=" &lt;div class=&quot;row answer-row&quot; style=&quot;margin-bottom: 5px;&quot; id=&quot;answer-nb-__name__&quot;&gt; &lt;div class=&quot;col-10&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;campaign_trigger_answers___name__&quot; name=&quot;campaign[trigger][answers][__name__]&quot; placeholder=&quot;Saisir une réponse&quot; class=&quot;answer-input form-control&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;col-2 text-right&quot;&gt; &lt;a href=&quot;#&quot; data-index=&quot;__name__&quot; class=&quot;remove-answer btn btn-danger&quot;&gt;X&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; "></div></fieldset>

使用AnswerType,form_row()生成以下标记:

<fieldset class="form-group"><div id="campaign_trigger_answers"></div></fieldset>

如您所见,prototypeAnswersType 不再生成任何属性,即使我已将该选项设置为 true。我的错误在哪里?

标签: phpformssymfonycollections

解决方案


推荐阅读