duanpie2414 2014-04-10 05:09
浏览 103
已采纳

如何在Symfony 2中向提交的表单添加额外数据?

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?
    }

}
  • 写回答

1条回答 默认 最新

  • dongqiao9015 2014-04-10 06:18
    关注

    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 ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?