沃梦达 / 编程问答 / php问题 / 正文

Symfony 2 带有文件类型的表单集合字段

Symfony 2 Form collection field with type file(Symfony 2 带有文件类型的表单集合字段)

本文介绍了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 带有文件类型的表单集合字段

基础教程推荐