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:
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:
class File
{
// properties
public $file; // this holds an UploadedFile object
// getters, setters
}
FileType:
....
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file', [
'required' => false
])
;
}
Product:
class Product
{
// properties
private $images; // ManyToMany relationship
// setters, getters
}
ProductType:
->add('images', 'collection', [
'type' => 'YOUR_FILE_TYPE_NAME',
'by_reference' => false,
'required' => false
])
Product contoller:
public function someAction()
{
...
$image = new File();
$product->addImage($image);
}
I know this solution can be overkill and creates extra tables, but it works.