Symfony2 - How to use a Data Transformer inside EventListeners

后端 未结 2 1872
无人及你
无人及你 2021-01-28 00:41
  • I need to use an Event Listener since I need different things to be displayed in my form whether it is new or an already existing entity. I can manage that.

2条回答
  •  忘了有多久
    2021-01-28 01:27

    Short answer: You can´t add the transformer inside the listener because the form is already locked.

    Long answer: There are some solutions. The most common, at least for me, is to a create a Custom form type where you add your transformer. Then you add your custom form how you would normally do in the event listener:

    class ElementCustomType extends AbstractType {
    
        private $em;
    
        public function __construct(EntityManager $entityManager)
        {
            $this->em = $entityManager;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options) {
    
            $builder
                ->addModelTransformer(new ElementObjToStringTransformer($this->em))
            ;
        }
    
        public function getParent() {
            return 'text';
        }
    
        public function getName() {
            return 'elementCustom';
        }
    }
    

    Define your form as a service:

     app.form.type.custom_element:
        class: AppBundle\Form\Type\ElementCustomType
        arguments: [@doctrine.orm.entity_manager]
        tags:
            - { name: form.type, alias: elementCustom }
    

    Use the form in the listener as your would normally do:

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){
            $element = $event->getData();
            $form = $event->getForm();
            $form->add('element', 'elementCustom')
        });
    

提交回复
热议问题