[英]Symfony 2 Form collection field with type file
我想用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,並使用集合的表單原型,javascript和按鈕來添加文件字段。
基於文檔的示例( 集合 - 添加和刪除 )
表格:
<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>
這只是一個想法,根據您的需要還有很多工作要做。 如果這不是您想要的,也許您可以調用添加按鈕單擊作為解決方法。
如果要顯示多個輸入字段,則不起作用。 集合類型要求您在渲染字段之前提供一些數據。 我已經嘗試過,然后創建了一個單獨的實體(例如File)並添加了與我的目標實體的關系。
例:
class File
{
// properties
public $file; // this holds an UploadedFile object
// getters, setters
}
文件類型:
....
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file', [
'required' => false
])
;
}
產品:
class Product
{
// properties
private $images; // ManyToMany relationship
// setters, getters
}
產品類別:
->add('images', 'collection', [
'type' => 'YOUR_FILE_TYPE_NAME',
'by_reference' => false,
'required' => false
])
產品控制器:
public function someAction()
{
...
$image = new File();
$product->addImage($image);
}
我知道這個解決方案可能會過度使用並創建額外的表,但它可以工作。
您需要在集合中指定窗口小部件的類型
請查看: http : //symfony.com/doc/2.0/reference/forms/types/collection.html
$builder->add('pictures', 'collection', array(
// each item in the array will be an "email" field
'type' => 'file',
// these options are passed to each "email" type
'options' => array(
'required' => false,
),
));
為了進一步閱讀,我建議
http://symfony.com/doc/2.0/reference/forms/types/file.html
此外,你需要添加sth到這個集合來顯示cuz它在初始化時將是空的,就像你的實體的構造函數。
表單類中的代碼是正確的,但您還應該修改表單域的名稱。 在您的情況下, full_name
應該是form[pictures][]
的形式。
實際上似乎在sf2.3中不再可以修改表單字段名稱,但是在sf2.4中它將是可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.