2014-04-12 37 views
1

我想提取並保存上傳圖像的EXIF數據。對於形我用如何在Symfony2中存儲基於用戶提交表單的其他數據?

<?php 

namespace Timeline\DefaultBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
use Timeline\DefaultBundle\Form\EventListener\DocumentListener; 

class DocumentType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('file') 
      ->add('upload', 'submit') 
      ->addEventSubscriber(new DocumentListener()); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'Timeline\DefaultBundle\Entity\Document', 
     )); 
    } 

    public function getName() 
    { 
     return 'document'; 
    } 
} 

然後,我有一個監聽器類:

<?php 


namespace Timeline\DefaultBundle\Form\EventListener; 

use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 



class DocumentListener implements EventSubscriberInterface{ 



    public static function getSubscribedEvents() 
    { 
     return array(
      FormEvents::POST_SUBMIT  => 'onPostSubmit' 
     ); 
    } 

    public function onPostSubmit(FormEvent $event) 
    { 
     $form = $event->getForm(); 

     $form->add('exif','collection',array('data' => array("a" => 'some data',"b" => "some data","c" => "some data"))); 
    } 

我是,如果我使用POST_SUBMIT我得到的錯誤無法孩子添加到提交表單的問題

如果我使用PRE_SUBMIT它存儲了密鑰,但不是數據{"a":null,"b":null,"c":null}

如何在文件上傳後添加EXIF數據?

回答

0

像這樣:

$event->getForm()->getParent() 

需要基本字段添加到窗體的父。所以下面應該工作:

public function onPostSubmit(FormEvent $event) 
    { 
     $form = $event->getForm()->getParent(); 

     $form->add('exif','collection',array('data' => array("a" => 'some data',"b" => "some data","c" => "some data"))); 
    } 
+0

感謝,但我得到'''FatalErrorException:錯誤:調用一個成員函數在''' – ed209

+0

中的非對象上添加()是否看過http://symfony.com/doc/currentbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data –

+0

是的,但是那裏的數據是另一個實體。我不確定我在做什麼錯我的代碼 - 只是想保存一個數組。 – ed209

0

您需要使用$formModifier回調,在你buildForm嘗試包括這樣的:

$formModifier = function (FormInterface $form) { 
    $form->add('exif','collection',array('data' => array("a" => 'some data',"b" => "some data","c" => "some data"))); 
}; 

$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) { 
    $formModifier($event->getForm()); 
}); 

FormModifier更詳細的http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms

解釋 - 編輯

爲此,您需要使用以下語句

use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 
use Symfony\Component\Form\FormInterface; 

此外,如果你用這種方法去,你可以刪除你的

->addEventSubscriber(new DocumentListener()) 

您的初始$builder通話

相關問題