Skip to content

Commit 0c54b8a

Browse files
committed
Add two tips about converting to File instance after fetching
1 parent f6068c9 commit 0c54b8a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

cookbook/controller/upload_file.rst

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,21 @@ You can use the following code to link to the PDF brochure of an product:
203203
View brochure (PDF)
204204
</a>
205205

206+
.. tip::
207+
208+
When creating a form to edit an already persisted item, the file form type
209+
still expects a :class:`Symfony\\Component\\HttpFoundation\\File\\File`
210+
instance. As the persisted entity now contains only the relative file path,
211+
you first have to concatenate the configured upload path with the stored
212+
filename and create a new ``File`` class::
213+
214+
use Symfony\Component\HttpFoundation\File\File;
215+
// ...
216+
217+
$product->setBrochure(
218+
new File($this->getParameter('brochures_directory').'/'.$product->getBrochure())
219+
);
220+
206221
Creating an Uploader Service
207222
----------------------------
208223

@@ -411,4 +426,30 @@ This listeners is now automatically executed when persisting a new Product
411426
entity. This way, you can remove everything related to uploading from the
412427
controller.
413428

429+
.. tip::
430+
431+
This listener can also create the ``File`` instance based on the path when
432+
fetching entities from the database::
433+
434+
// ...
435+
use Symfony\Component\HttpFoundation\File\File;
436+
437+
// ...
438+
class BrochureUploadListener
439+
{
440+
// ...
441+
442+
public function postLoad(LifecycleEventArgs $args)
443+
{
444+
$entity = $args->getEntity();
445+
446+
$fileName = $entity->getBrochure();
447+
448+
$entity->setBrochure(new File($this->targetPath.'/'.$fileName));
449+
}
450+
}
451+
452+
After adding these lines, configure the listener to also listen for the
453+
``postLoad`` event.
454+
414455
.. _`VichUploaderBundle`: https://github.com/dustin10/VichUploaderBundle

0 commit comments

Comments
 (0)