Symfony2 Upload multiple files

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

Answers


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


Need Your Help

batch file to launch an executable file which requires input

windows shell batch-file cmd command-prompt

I have an executable file that requires a user to input a file name to run. The exe file will then output a file when it finishes. (For example, when I run the exe file, it opens in command promp...

why is my javascript object method returning undefined?

javascript oop

I'm a beginner in both javascript oop and game programming too(!) .