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.
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')
});