[英]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 %}
My problem is that data-prototype attribute doesn't include the span tag; 我的问题是data-prototype属性不包含span标记; it only contains the output of
{{ form_row(player.name) }}
. 它只包含
{{ form_row(player.name) }}
的输出。 Is there a way to include the whole content of div#template
in the data-prototype
attribute? 有没有办法在
data-prototype
属性中包含div#template
的全部内容?
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 :)
我想出了一个应该做的诀窍:)
First - I think your <div id="team" data-prototype="...">
should be outside your loop. 首先 - 我认为你的
<div id="team" data-prototype="...">
应该在你的循环之外。
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'.
注意:autoescape对包含的内容没有影响,因此请使用“过滤器转义”。
<div id="playerFields" data-prototype="{% filter escape %}{% include 'AcmeTeamBundle:Team:prototypePlayer.html.twig' with {'form': form.players.get('prototype')} %}{% endfilter %}">
Then in your prototypePlayer.html.twig, just render each field as you normally would in a form view. 然后在prototypePlayer.html.twig中,只需像往常一样在表单视图中渲染每个字段。
<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 :) 我的模板与您的问题有不同的数据结构,但它应该有帮助:)
Cheers, 干杯,
Chris 克里斯
As of Symfony 2.1, .get()
is deprecated and the above will not work. 从Symfony 2.1开始,不推荐使用
.get()
,以上内容不起作用。 Replace form.players.get('prototype')
with form.players.vars.prototype
to fix this in later versions of Symfony. 更换
form.players.get('prototype')
与form.players.vars.prototype
在以后的版本的Symfony来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.