Reputation: 799
I have form with File Field Type. I would like to "catch" uploaded file in controller but I don't know how to do it.
I tried to get access via $form->get('file')
, but seems to me that this is the wrong way to go. Why? var_dump( $form->get('file') );
return string with a filename (and nothing more)! I expected the object or something like that, but I got only a filename.
Upvotes: 0
Views: 8086
Reputation: 4835
Do this if you just want to get the file from the form:
$myFile = $request->files->get('inputFieldFileId');
this should be all you need
Upvotes: 9
Reputation: 3523
When you set up your form and entity right symfony will handle it automatically.
Example set up:
Entity (Document has a file)
<?php
namespace Acme\DemoBundle\Entity\Document;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Document
{
/**
* @var UploadedFile
*/
protected $file;
/**
* @param UploadedFile $file - Uploaded File
*/
public function setFile($file)
{
$this->file = $file;
}
/**
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
//add functions described here: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
}
FormType
<?php
namespace Acme\DemoBundle\Entity\DocumentType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class DocumentType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Document'
));
}
/**
* @return string
*/
public function getName()
{
return 'acme_demo_document';
}
}
Controller snippet ( probably createAction
and updateAction
)
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
\Doctrine\Common\Util\Debug::dump($entity->getFile());
$entity->getFile()
will hold the file.
Take a look here: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html for instructions on how to implement moving the file from /temp to e.g. web/uploads
and other things.
If your IDE doesn't show you what you can do with the UploadedFile
you can look it up here: http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html
Upvotes: 3