Symfony 2 Form collection field with type file(Symfony 2 带有文件类型的表单集合字段)
问题描述
我想通过 POST 请求(不带 Ajax)上传多个文件.我可以将 Symfony 2 的表单集合字段与这样的类型文件一起使用吗:
I want to upload multiple files with POST request (without Ajax). Can I use Symfony 2's form collection field with type file like this:
实体中的代码:
public $pictures;
public function __construct()
{
$this->pictures = new DoctrineCommonCollectionsArrayCollection();
}
表单类中的代码:
$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 %}
我试过了,但它似乎不起作用.它没有显示任何错误,但也没有显示输入文件.有什么想法吗?
I tried, but it doesn't seem to work. It is not showing any errors, but it is not showing the input file either. Any ideas?
推荐答案
要实际呈现输入类型,您需要将集合中的 allow_add 选项设置为 true 并使用集合的表单原型、javascript 和添加按钮文件字段.
To actually render input types you will need to set the allow_add option in the collection to true and use the form prototype of the collection, javascript and a button to add file fields.
基于文档的示例 (集合-添加和删除)
形式:
<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>
这只是一个想法,根据您的需要还有很多工作要做.如果这不是您想要的,也许您可以调用添加按钮单击作为一种解决方法.
This is just an idea, there is still plenty to do depending on your needs. If this wasn't what you were looking for, maybe you could call the add button click as a workaround.
这篇关于Symfony 2 带有文件类型的表单集合字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony 2 带有文件类型的表单集合字段
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01