Symfony2: Edit file upload
Asked Answered
D

3

6

I am using the cookbook article from symfony.com to implement a file upload option for images.

Now I want to load up other images to the entity.

The default strategy for editing is: 1. Fetch out of DB 2. Inject into Form 3. Persist

Somehow this strategy doesn't work anymore when using file uploads (doctrine doesn't execute the events)

What else could I do to make the articles with picture editable?

Delanadelancey answered 1/4, 2012 at 8:10 Comment(0)
D
10

The cookbook does not handle updates, in particular in the case where only the file changes.

In this case, the PreUpdate event is not triggered, so you need to trigger $entity->preUpload() manually before the $em->persist($entity), so that the file upload gets handled in any case (preUpload will alter $entity->path so the persisting will occur)

Desai answered 2/4, 2012 at 14:44 Comment(2)
Hi, youre right. When no field is updated the lifecycle callback events doesn't get fired :)Delanadelancey
If you use the Knp DoctrineExtensions, you can use Timestampable on the entity holding the file upload logic and use $entity->updateTimestamps(); before $em->persist() so it will updated the dummy fields you need ;)Alan
G
7

If you change only the upload field the lifecycle not run the upload method, In the cookbook is reported the solution in a quote box as below:

The PreUpdate and PostUpdate callbacks are only triggered if there is a change in one of the entity's field that are persisted. This means that, by default, if you modify only the $file property, these events will not be triggered, as the property itself is not directly persisted via Doctrine. One solution would be to use an updated field that's persisted to Doctrine, and to modify it manually when changing the file.

add a dummy field to update in the controller before persist event as suggest by this duscussion:

https://github.com/symfony/symfony-docs/pull/564

public function setFile(UploadedFile $file)
{
    $this->file = $file;
    $this->updatedAt = new \DateTime();
}
Gerladina answered 9/8, 2013 at 12:48 Comment(0)
E
0

I have was in similar situation. I try to edit existing record in database with path to the file. When i edit record i must upload new file, what is not comfortable for users. In my solution i use variable tmp file for file hash and variable file name. All needed operation i made in Action edit class.

Full example action class in bellow link

https://github.com/marekz/php_examples/wiki/Symfony-how-to-edit-attachment-form

Empyema answered 7/8, 2018 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.