我创建了一个Symfony Poll-Bundle,它的Entitys Campaign->Block->Line->Field->PollResult。所以我有一个由许多块组成的CollectionType CampaignType。一个块由许多行组成。一行由多个字段组成。(例如,一行是发烧的线,字段是强度,以及发烧发生的时间和到期时间),并且每个字段都有一个PollResult,其中包含填写活动的用户的答案。
现在,我想让用户能够将新字段添加到行中,例如,进入第二个发烧期。所以我需要一个‘添加一条线’-按钮为每一条线,复制这一行。
我使用this documentation做到了这一点。
首先,我在我的LineType FormBuilder中添加了'allow_add' => true:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('userAddFlag');
    $builder->add('fields', CollectionType::class, array(
        'entry_type' => FieldType::class,
        'entry_options' => array('label' => false),
        'allow_add' => true,
    ));
}然后,我使用data-prototype将其添加到我的视图中:
<ul class="fields" data-prototype=" {{ form_widget(line.fields.vars.prototype)|e('html_attr') }} ">
    <li>
        {% for field in line.fields %}
            <div>
                {% for pollResult in field.pollResults %}
                    <div class="formLabelDiv">{{ field.vars.value.getTranslationName(app.request.getLocale()) }}</div>
                    <div class="formWidgetDiv">{{ form_widget(pollResult) }}</div>
                {% endfor %}
            </div>
        {% endfor %}
    </li>
</ul>最后我添加了这段jQuery代码:
<script>
    var $collectionHolder;
    //setup an "add a Line" Link
    var $addLineButton = $('<button type="button" class="add_line_link">Add a Line</button>');
    var $newLinkLi = $('<li></li>').append($addLineButton);
    jQuery(document).ready(function (){
        //Get the ul that holds the collection of fields
        $collectionHolder = $('ul.fields');
        //add the "add a line" anchor and li to the tags ul
        $collectionHolder.append($newLinkLi);
        //count the current form inputs we have, use that as the new index when inserting a new item
        $collectionHolder.data('index', $collectionHolder.find(':input').length);
        $addLineButton.on('click', function (e){
            addFieldsForm($collectionHolder, $newLinkLi);
        })
    })
    function addFieldsForm($collectionHolder, $newLinkLi){
        //get the data-prototyp
        var prototype = $collectionHolder.data('prototype');
        //get the new index
        var index = $collectionHolder.data('index');
        var newForm = prototype;
        $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);
        $newLinkLi.before($newFormLi);
    }
</script>现在“添加一行”按钮出现在页面上,但它没有添加任何内容。如何添加新字段,以及如何复制整行,而不是只向添加的行添加一个字段(我希望有三个字段强度(Dropdown)、from和due(都是带日期选择器的文本字段))
发布于 2020-11-25 02:10:23
尝试向LineType.php添加'by_reference' => false,
https://stackoverflow.com/questions/64983433
复制相似问题