multiple file upload in Symfony2 example

file upload

Multiple File Upload in Symfony framework

I spent decent amount of time to put together the multiple file upload in symfony.

It is not that difficult actually but the problem is there is no direct/easy documentation or tutorial on it.

On the form type where you would build the form, have the files with the type of collection and make its type a file entity. In this case there would be two file types by default.

    public function buildForm(FormBuilderInterface $builder, array $options) 
    {
        /*
         * The file does not need to be added as "file" because it is referred
         * in the validation for File and SF will automatically know it is file.
         */
        return $builder
                ->add("files", 'collection', array(
		    'type'=>new FileType(),
		    'allow_add'=>true,
		    'data'=>array(new BundleEntityFile(),
		    new BundleEntityFile())
		))
                ->add('save', 'submit');
    }

    public function getName()
    {
        return "files";
    }
}

The trick is on adding the files as collection. Initially, we have two file inputs and their type being FileType.

The allow_add is important to be able to add files through javascript.

The javascript would look like:

/*Handling multiple picture upload*/
$('#add_pictures').click(function(){
    var total_files=$("#member_pictures_container li").length;
    var file_label=document.createElement("label");
    file_label.innerHTML="File";
    file_label.for="PhotoAndDescription_files_"+total_files;
    var div_file=document.createElement("div");    
    div_file.appendChild(file_label);
    var picture= document.createElement('input');
    picture.name="PhotoAndDescription[files]["+total_files+"][file]";
    picture.type="file";
    picture.id="PhotoAndDescripton_files_"+total_files;
    div_file.appendChild(picture);
    div_container=document.createElement('div');
    div_container.id="PhotoAndDescription_files_"+total_files;
    div_container.appendChild(div_file);
    var list_element=document.createElement('li');
    list_element.appendChild(div_container);
    $('#member_pictures_container').append(list_element);
});

FileType would look like:

class FileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        return $builder->add("file", "file");
    }

    public function getName()
    {
        return "filetype";
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'=>'BundleEntityFile',
            'csrf_protection'=>true,
            'csrf_field_name'=>'_token',
            'intention'=>'file'
        ));
    }
}

 

And the twig file would look like this one

{{form_start(form)}}
    {{ form_errors(form) }}
    {{ form_widget(form.about_member) }}
    • {% for file in form.files %}

 

  • {{ form_errors(file) }} {{ form_widget(file) }}

 

 

{% endfor %} {{form_end(form)}}

Pretty much this will take care of the multiple file handling in symfony2. As I mentioned earlier, it is not that difficult but the lack of documentation has made it so..

Do you know what to check to deploy Symfony app?

What is POST and HTTP-RAW-POST and php input has to do with enctype? Find out here

Using Facebook API to post articles from PHP

Post to Facebook From app – Using PHP

Consuming SOAP tutorial – Using java eclipse

connect to sftp from php

jQuery Select Option from Json

Passing composite object parameter to jersey in Restful Java web

11 Comments
  1. Deif

    you could also give a try with the uploader bundle, where you actually have multiple frontends available. it’s on packagist as well as on github (https://packagist.org/packages/oneup/uploader-bundle)

    1. gullele

      Thanks a lot for sharing Deif, I will give it a try on my other upcoming project.

  2. Mirken

    Can you post the entire code for the form. How many FileType classes do you have?

  3. Gazeboo

    Thx man! I’ve been struggling for 10 hours looking for this solution;) Works fine with VichUpoaderBundle.

    1. gullele

      Glad that helped you Gazeboo! And thanks for taking your time and commenting.

  4. Deogracias Maroto Romero

    Hello! Nice article, but I’m struggling with something maybe I should know already but well, I’m stuck. About the File Entity, The “files” field has to be declared (with getters and setters returning arrays)? or I’m just in the wrong path? would you be able to post some example?

    1. gullele

      Hello Deogracias, I will post the code part you are looking for tonight. Stay tuned :)

      1. joe

        Any news on posting the code to the File entity you were using?

      2. romeo crennel

        Can we get the entity you’re using please?

  5. Massimiliano

    Hi,

    I’m Massimiliano and I am a beginner, I spent decent amount of time to put together the multiple file upload in symfony too, I looked for a solution to this for a long time, I finally found this post, it’s very good, but please i need the complete simply code example, with the namespaces, controller, entity and type file etc, if you can, you are the best.

    Thank you very much

    1. gulleman

      Thanks Massmiliano, I will to find a time and put things together.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*