我想使用 POST 请求(不使用 Ajax)上传多个文件。我可以将 Symfony 2 的表单集合字段与这样的类型文件一起使用吗:
实体中的代码:
public $pictures;
public function __construct()
{
$this->pictures = new \Doctrine\Common\Collections\ArrayCollection();
}
表单类中的代码:
$builder->add('pictures', 'collection', array(
'type' => 'file',
'required' => false,
'attr' => array(
'multiple' => 'multiple'
)
));
Twig 中的代码:
{% for picture in form.pictures %}
<td>
{{ form_widget(picture) }}
</td>
{% endfor %}
我试过了,好像不行。它没有显示任何错误,但也没有显示输入文件。有什么想法吗?
最佳答案
要实际呈现输入类型,您需要将集合中的 allow_add 选项设置为 true 并使用集合的表单原型(prototype)、javascript 和一个按钮来添加文件字段。
基于文档的示例 (Collection- adding and removing)
形式:
<form action="..." method="POST" {{ form_enctype(form) }}>
{# ... #}
{# store the prototype on the data-prototype attribute #}
<ul id="image-container" class="collection-container" data-prototype="{{ form_widget(form.images.vars.prototype) | e }}">
{% for imageField in form.images%}
<li>
{{ form_widget(imageField) }}
</li>
{% endfor %}
</ul>
<a href="#" class="collection-add" data-collection="image-container">Add image</a>
</form>
脚本:
<script type="text/javascript">
var imageCount;
jQuery(document).ready(function() {
$(document).on('click', '.collection-add', function () {
var $collectionContainer = $('#' + $(this).data('collection'));
if(!imageCount){imageCount = $collectionContainer.children().length;}
var prototype = $collectionContainer.attr('data-prototype');
var item = prototype.replace(/__name__/g, imageCount);
$collectionContainer.append(item);
imageCount++;
});
})
</script>
这只是一个想法,根据您的需要还有很多事情要做。 如果这不是您想要的,也许您可以调用添加按钮点击作为解决方法。
关于php - 带有类型文件的 Symfony 2 表单集合字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12410578/