如何自定义 CollectionType() 项目? [英] How to customize a CollectionType() item?
问题描述
这个§Symfony2 文档 展示了一种用于自定义单个字段的出色技术.我经常使用它,但有一个特定的 Type
我很难进行自定义:CollectionType()
自定义集合本身非常很简单,你可以这样做:
This § of the Symfony2 documentation shows an awesome technique for customizing an individual field. I'm using it a lot but there is one particular Type
for which I'm having a hard time doing the customization : the CollectionType()
Customizing the collection itself is quite easy, you can do something like this:
{% block _mynamespace_mybundle_mytype_mycollectionfield_row %}
{% if prototype is defined %}
{% set attr = attr|merge({'data-prototype': form_widget(prototype) }) %}
{% endif %}
{% spaceless %}
<ul {{ block('widget_container_attributes') }}>
{% spaceless %}
{{ form_errors(form) }}
{% for child in form %}
<li>
{{form_widget(child)}}
</li>
{% endfor %}
{% endspaceless %}
{{ form_rest(form) }}
</ul>
{% endspaceless %}
{% endblock %}
但是如何自定义集合的每个元素?以及如何使用 Twig 自定义 data-prototype
(data-prototype
是用于使用 js 添加新项目的特殊属性)?
But how can you customize each element of the collection ? And how can you customize the data-prototype
using Twig (the data-prototype
is a special attribute used to add new items with js)?
我尝试做这样的事情(对于 data-prototype
):
I tried doing something like this (for the data-prototype
):
{% block _mynamespace_mybundle_mytype_mycollectionfield_$$name$$_row %}
customization ok!
{% endblock %}
但是我得到错误,因为我不知道如何转义 $
But I get errors, because I don't know how to escape the $
关于项目,我尝试了很多东西:
Regarding the items, I tried many things:
{% block _mynamespace_mybundle_mytype_mycollectionfield_item_subfield_row %}
customization ok!
{% endblock %}
{% block _mynamespace_mybundle_mytype_mycollectionfield_element_subfield_row %}
customization ok!
{% endblock %}
它们都不起作用.
推荐答案
我在 symfony 的 bug tracker 中问了这个问题,似乎没有解决方案,但一个好的解决方法是为每个要自定义的子字段创建自定义类型.请参阅这个问题
I asked the question in symfony's bug tracker, and it seems there is no solution, but a good workaround is creating a custom type for each subfield you want to customize. See this issue
这篇关于如何自定义 CollectionType() 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!