Search code examples
symfonysymfony3

Empty $request->files (FileBag) when using a custom form (not the built in Type from SF)


I'm having issues with file uploads... I'm adding manually a few inputs within a Symfony form (Offer) to allow the user to create a new Company if he doesn't want to use one that already exists, it works very well for the text/textarea fields, but my file Input doesn't work properly. Its content appears in the request parameters instead of in the files parameters of my Request, see below what I get when I dump($request) :

 OfferController.php on line 173:
Request {#86 ▼
  +attributes: ParameterBag {#70 ▶}
  +request: ParameterBag {#69 ▼
    #parameters: array:2 [▼
      "offer" => array:15 [▶]
      "company" => array:6 [▼
        "name" => "entreprise"
        "pic_logo" => "ah.png" //THIS SHOULD NOT BE HERE BUT IN THE FILEBAG
        "sector" => "2"
        "status" => "fdsfds"
        "revenues" => "sdfsdf"
        "content" => "<p>sdfdsf</p>\r\n"
      ]
    ]
  }
  +query: ParameterBag {#49 ▶}
  +server: ServerBag {#73 ▶}
  +files: FileBag {#63 ▼
    #parameters: [] //NO FILE HERE :'(
  }

Here is the code that produces this : View :

{{ form_start(form) }}

    <h2>Employeur</h2>
    {{ form_row(form.company) }}

    <a class="company-new" href="#" id="toggleCompanyForm">Ajouter une nouvelle entreprise...</a>

    <div id="form_company" style="display:none">
        <div class="row">
            <div class="large-6 small-12">
                <label>Nom de l'entreprise</label>
                <input type="text" name="company[name]">
            </div>
            <div class="large-6 small-12">
                <label>Logo de l'entreprise</label>
                {% for message in app.session.flashBag.get('warning_logo') %}
                    <div class="alert alert-warning">
                        {{ message }}
                    </div>
                {% endfor %}
                <input type="file" name="company[pic_logo]"> {# MY FILE INPUT #}
            </div>

And the controller :

public function createAction(Request $request)
{
    $confirmed = false;
    $entity = new Offer();

    $em = $this->getDoctrine()->getManager();
    $sectors = $em->getRepository('ModelBundle:Sector')->findAll();

    $form = $this->createForm('ModelBundle\Form\OfferType', $entity);
    $session    = $request->getSession();

die(dump($request));


Solution

  • To upload a file through HTML form you have to add enctype="multipart/form-data" to the tag:

    <form action="..." method="post" enctype="multipart/form-data">
    

    Or change opening form tag in twig:

    {{ form_start(form, {'multipart': true}) }}