【发布时间】:2014-05-18 21:05:47
【问题描述】:
我在我的 symfony 2 应用程序中使用以下抽象类型来编辑专辑
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
->add('description', 'textarea')
->add('public', 'checkbox')
->add('lists', 'collection', array(
'attr' => array('data-category' => 'access-right'),
'type' => 'albumListType',
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
)
)
->add('medias', 'collection', array(
'attr' => array('data-category' => 'media'),
'type' => new MediaType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
)
)
;
}
当我显示此表单时,我需要为与文章链接的每个媒体显示缩略图,以便 我尝试重载 mediawidget 以生成以下 html
<div class="row" id="albumtype_media" data-prototype="prototype">
<div class="col-md-3" id="albumtype_media_0">
<img src="path"/>
<input type="hidden" name="albymtype_media[0][path]" value="path"/>
</div>
<div class="col-md-3" id="albumtype_media_1">
<img src="path"/>
<input type="hidden" name="albymtype_media[1][path]" value="path"/>
</div>
</div>
为了实现这一点,我使用了一个特殊的表单主题来自定义媒体小部件
{% block _medias_widget %}
{% spaceless %}
{% if prototype is defined %}
{% set attr = attr|merge({'data-prototype': form_row(prototype) }) %}
{% endif %}
<div class="row" {{ block('widget_container_attributes') }}>
{{ block('collection_media_rows') }}
{{ form_rest(form) }}
</div>
{% endspaceless %}
{% endblock %}
{% block collection_media_rows %}
{% spaceless %}
{{ form_errors(form) }}
{% for innerform in form %}
{% spaceless %}
<div class="col-md-3" {{ block('widget_attributes') }}>
{% if form.parent is empty %}
{{ form_errors(innerform) }}
{% endif %}
<img src="{{ innerform.vars.value.path }}"/>
{% for child in innerform %}
{{ form_errors(child) }}
{{ form_label(child) }}
{{ form_widget(child) }}
{% endfor %}
</div>
{% endspaceless %}
{% endfor %}
{% endspaceless %}
{% endblock %}
给我以下输出
<div class="row" id="albumtype_media" data-prototype="prototype">
<div class="col-md-3" id="albumtype_media" data-prototype="prototype">
<img src="path"/>
<input type="hidden" name="albymtype_media[0][path]" value="path"/>
</div>
<div class="col-md-3" id="albumtype_media" data-prototype="prototype">
<div id="albumtype_media_1">
<input type="hidden" name="albymtype_media[1][path]" value="path"/>
</div>
</div>
当我从 symfony 2 开始时,我对 twig 并没有很好的理解,查看 form_widget 的源代码也对我没有帮助,所以如果你能解释我如何获得所需的结果,我会非常太棒了。
【问题讨论】:
-
你可以尝试使用symfony form type extension