I can do $this->createForm(new EntityType(), $entity, array('em' => $em))
from the controller, but how can I pass it to a NestedEntityType()
? I guess I can't just pass it on from inside the EntityType->buildForm()
:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$entityManager = $options['em'];
$builder->add('entities', 'collection', array(
'type' => new NestedEntityType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
));
}
I need the entity manager to setup a data transformer to check if an entity already exists in the database, and use that entity in a relationship instead of creating a new one with the same name.
Resources
You could define your form as a service and then inject Doctrine entity manager in it as an argument.
http://symfony.com/doc/3.4/form/form_dependencies.html
And then declare the service like this:
services:
acme.type.employee:
class: Acme\AcmeBundle\Form\Type\FormType
tags:
- { name: form.type, alias: form_em }
arguments: [@doctrine]
And in the form type:
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
/** @var \Doctrine\ORM\EntityManager */
private $em;
/**
* Constructor
*
* @param Doctrine $doctrine
*/
public function __construct(Doctrine $doctrine)
{
$this->em = $doctrine->getManager();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With