Reputation: 11293
I have a simple form that only uploads an image. However, in my database I want to extract and record some EXIF data from that image.
I'm not sure what to use in Symfony2. It does't seem like the right place to calculate this extra information in the Entity. Where else could I put it?
<?php
namespace Timeline\DefaultBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
//...
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
// extract EXIF here?
}
}
Upvotes: 0
Views: 3104
Reputation: 669
Doctrine events can work nicely as long as you don't need to modify another entity.
I think the best way to handle your case would be to use form events. http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-user-data
For example you could use a POST_SUBMIT event, and dynamically add a 'exif' text field, and on your entity a $exif property mapping your database field.
class Document
{
/**
* @ORM\Column(type="text")
*/
private $exif;
}
class DocumentType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file')
;
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
$data['exif'] = 'data';
$event->setData($data);
$form->remove('exif');
$form->add('exif', 'string');
}
);
}
}
Edit #1 : After further research, the only way I found is to define 'exif' key in data array and 'exif' field in form, so it will be able to mapped it to your entity. I didn't found a way to solve the problem of the remaining 'exif' field in the form after submission. If you define it as hidden, or do not use {{ form_rest() }}, it will not appear, but this not so clean ...
Upvotes: 3