I need to modify some fields in my form (label and class), based on whether the entity is the latest published version or not. So I need to be able to inject the entity mana
You created a new ViewType without passing the EntityManager. Get the form type from the dic with
$form = $this->createForm($this->get('gutensite_cms.form.type.view'), $view);
or create a new object with the entity manager as an argument
$form = $this->createForm(new ViewType($this->getDoctrine()->getManager()), $view);
You got that error because you`re creating form type like this:
$form = $this->createForm(new ViewType(), $view);
You create new object ViewType
without any arguments and it needs to be called with EntityManager
. You can simply pass entity manager from controller, like this:
$em = $this->get('doctrine.orm.entity_manager'); // or doctrine.orm.billing_entity_manager
$form = $this->createForm(new ViewType($em), $view);
In this case you don't even need to define this form type as a service.
Use of doctrine.orm.entity_manager
or doctrine.orm.billing_entity_manager
depends on what you need to fetch inside ViewType
- (from witch database).
UPDATE:
Define form type as a service.
Add this two services to your configuration (services.yml
):
services
gutensite_cms.form.view:
factory_method: createNamed
factory_service: form.factory
class: Symfony\Component\Form\Form
arguments:
- view_form # name of the form
- view # alias of the form type
- null # data to bind, this is where your entity could go if you have that defined as a service
- { validation_groups: [Default] } # validation groups
gutensite_cms.form.type.view:
class: Gutensite\CmsBundle\Form\Type\ViewType
arguments: [ "@doctrine.orm.entity_manager" ]
tags:
- { name: form.type, alias: view }
Then you can create new form by executing this inside your controller (or whatever has container
) without manualy passing any arguments (they will be injected automaticly):
public function newAction()
{
$view = ...;
$form = $this->get( 'gutensite_cms.form.view' );
// set initial form data if needed
$form->setData( $view );
}
declare your form type as service:
...
<parameter key="gutensite_cms.form.type.view.class">Gutensite\CmsBundle\Form\Type\ViewVersionType</parameter
...
...
<service id="gutensite_cms.form.type.view" class="%gutensite_cms.form.type.view.class%">
<argumet type="service" id="doctrine.orm.CMS_OR_BILLING_entity_manager" />
<tag name="form.type" alias="YOUR_FORM_TYPE_NAME" />
</service>
...
in your form type:
...
private $em;
public function __construct(EntityManagerInterface $entityManager) {
$this->em = $entityManager;
}
or ou can inject whole container and use it like this:
$this->container->get('doctrine')->getManager('cms'); // or billing