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:
Code in Entity:
public $pictures;
public function __construct()
{
$this->pictures = new \Doctrine\Common\Collections\ArrayCollection();
}
Code in Form Class:
$builder->add('pictures', 'collection', array(
'type' => 'file',
'required' => false,
'attr' => array(
'multiple' => 'multiple'
)
));
Code in 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?
The code in the form class is correct, but you also should modify the name of the formfield. The
full_name
should beform[pictures][]
in your case.It actually seems that modifying a form field name is not possible anymore in sf2.3, but it will be possible in sf2.4 again.
https://github.com/bamarni/symfony/commit/35639824e864ed8d4a4cc0d8360f2c73ae08b507#commitcomment-3627879
You need to specify the type of the widget in collection
Look at the: http://symfony.com/doc/2.0/reference/forms/types/collection.html
For further reading I suggest
http://symfony.com/doc/2.0/reference/forms/types/file.html
Also you need to add sth to this collection to display cuz it will be empty when initialize like in your constructor of entity.
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.
An example based in the documentation (Collection- adding and removing)
The form:
The 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.
If you want to show multiple input fields, no, it won't work. A collection type requires you to supply some data before rendering the fields. I've already tried it, and came up creating a separate entity (e.g. File) and and adding relationship to my target entity.
example:
FileType:
Product:
ProductType:
Product contoller:
I know this solution can be overkill and creates extra tables, but it works.