6

I've tried to upload file using a form without an entity class. No luck so far.

  // Controller
  public function uploadAction() {
    $request = $this->getRequest();
    $form = $this->createFormBuilder()
            ->add('images', 'file') // If I remove this line data is submitted correctly
            ->add('dir', 'text')
            ->getForm();

    if ($request->getMethod() == 'POST') {
      $request = $this->getRequest();
      $form->bindRequest($request);

      $data = $form->getData();
      var_dump($data);
    }   
    else
      return $this->render('OverseerMainBundle:Default:form.html.twig', array(
          'form' => $form->createView(),
      )); 
  }

// form.html.twig
{% block body %}
<form action="{{ path('OverseerMainBundle_upload') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    <input type="submit" />
</form>
{% endblock %}

So far var_dump echoes:

array(2) { ["images"]=> NULL ["dir"]=> NULL }

However if I remove line ->add('images', 'file') everything is ok:

array(1) { ["dir"]=> string(4) "test" }

P.S. I've checked html code of form and attribute enctype="multipart/form-data" is presented. So it's not an issue.

2 Answers 2

6

Also I hope this would help others:

if ($form->isValid()) {
        $file = $form->get('file')->getData();
        $name = $file->getClientOriginalName();
        $dir = __DIR__.'/../../../../web/uploads';

        $file->move($dir, $name) ;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Does anyone know why $form->get('file')->getData() is not working in Symfony 2.7.40 ? It returns null.
Found the answer, it's v2.7.38 that introduced a BC by fixing a security bug github.com/symfony/symfony/pull/24993
I have stopped using 2.7 and bellow. I have jumped from 2.3 to 2.8 and I am currently preparing for 3.4.
2

Have you checked that the file doesn't exceed the server maximum file size limit? The default is 2MB. I haven't used Symfony 2.0 yet so I am not sure of that.

1 Comment

LOL, no worries man we all do it at one point or another. Have some more coffee.

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.