Symfony2:具有数据原型的收集表单字段类型 [英] Symfony2: collection form field type with data-prototype
问题描述
我有一个要向其添加玩家(玩家的对象)的团队.我已经正确设置了表单类型"类.这是我观点的相关部分:
I have a Team to which I would like to add players (objects of Player). I've set up the form "type" classes correctly. Here's the relevant part of my view:
{% for index, player in form.players %}
<div id="template" data-prototype="{{ form_widget(form.players.get('prototype')) | e }}">
<span class="title">{{ index }}</span>
{{ form_row(player.name) }}
</div>
{% endfor %}
我的问题是数据原型属性不包含span标记;它仅包含{{ form_row(player.name) }}
的输出.有没有办法将div#template
的全部内容包含在data-prototype
属性中?
My problem is that data-prototype attribute doesn't include the span tag; it only contains the output of {{ form_row(player.name) }}
. Is there a way to include the whole content of div#template
in the data-prototype
attribute?
推荐答案
这也困扰着我.我自定义了字段类型,甚至使用简化的字段集(用于更复杂的对象)制作了简单的表单类型,但是感觉并不对.我想出了一个应该解决这个问题的解决方案:)
This was bugging me too. I customized a field type and even made simple form types with a reduced fieldset (for more complex objects), but it just didn't feel right. I've come up with a solution that should do the trick :)
首先-我认为您的<div id="team" data-prototype="...">
应该在循环之外.
First - I think your <div id="team" data-prototype="...">
should be outside your loop.
接下来,您的原型只是一个表单视图对象,因此,如果将其传递给模板,则可以手动呈现字段并自定义输出.注意:自动转义对所包含的内容没有影响,因此请使用过滤器转义".
Next, your prototype is just a form view object, so if you pass it to a template you can render fields by hand and customize the output. Note: autoescape has no effect on included content, so use 'filter escape'.
<div id="playerFields" data-prototype="{% filter escape %}{% include 'AcmeTeamBundle:Team:prototypePlayer.html.twig' with {'form': form.players.get('prototype')} %}{% endfilter %}">
然后在您的prototypePlayer.html.twig中,像平常一样在表单视图中呈现每个字段.
Then in your prototypePlayer.html.twig, just render each field as you normally would in a form view.
<div>
<span class="title">{{ form_label(form.name) }}</span>
{{ form_row(form.name) }}
<span class="age">{{ form_label(form.age) }}</span>
{{ form_row(form.age) }}
{# render whatever else you like from your Form/PlayerType class... #}
<div>
我的模板具有与您的问题不同的数据结构,但是应该可以帮助:)
My template has a different data structure to your question, but it should help :)
干杯
克里斯
从Symfony 2.1开始,不推荐使用.get()
,并且以上内容均无效.将form.players.get('prototype')
替换为form.players.vars.prototype
可以在更高版本的Symfony中解决此问题.
As of Symfony 2.1, .get()
is deprecated and the above will not work. Replace form.players.get('prototype')
with form.players.vars.prototype
to fix this in later versions of Symfony.
这篇关于Symfony2:具有数据原型的收集表单字段类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!