1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.