您应该将新类型声明为服务并将实体管理器注入其中:
namespace Your\Bundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;
class NewExampleType extends AbstractType
{
protected $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
//your code
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
//your code
}
public function getParent()
{
return 'hidden';
}
public function getName()
{
return 'example_widget';
}
}
然后,在 services.yml 中声明新服务
services:
example.type:
class: Your\Bundle\Form\Type\NewExampleType
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: form.type, alias: "example_widget" }
来源:http ://symfony.com/doc/current/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service
然后,你应该看看这里:http ://symfony.com/doc/current/cookbook/form/data_transformers.html