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

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题