Reputation: 151
Hello everyone I still learning symfony2 and I want to handle uploading multiple files to server. I try execute 2 entities by one form. I have Document, Product entity and
form CreateProductType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text') // product name, quantity, description, etc
->add('file','file',array(
'required' => false,
'mapped' => false,
'data_class' => 'AppBundle\Entity\Document',
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple',
)
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product'
));
}
what I supposed to do in controller to put files to uploads folder, insert new product
name,description,quantity,price, etc
and document (photos)
id, path, product_id
to database? Thanks in advance.
EDIT. my Document entity looks like this Document.php
Upvotes: 1
Views: 526
Reputation: 3755
If use form multiple array you should use collection in builder:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('files', 'collection', array(
'type' => 'file',
'options' => array(
'required' => false,
'mapped' => false,
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple',
)
)
))
->add('product', new ProductType())
->add('save', 'submit', array(
'label' => 'Submit',
'attr' => array('class' => 'btn btn-default')
));
}
and then use array collection in entity:
/**
* @Assert\File(maxSize="6000000")
*/
public $files;
public function __construct()
{
$this->files = new ArrayCollection();
}
/**
* Add file
*
* @param UploadedFile $file
* @return UploadedFile
*/
public function addFile(UploadedFile $file)
{
$this->files[] = $file;
return $this;
}
/**
* Remove file
*
* @param UploadedFile $file
*/
public function removeFile(UploadedFile $file)
{
$this->files->removeElement($file);
}
Because multiple upload need has an array name name="files[]"
to store file multiple.
SEE: Multiple file upload with Symfony2 and Symfony 2 Form collection field with type file
Upvotes: 1