Symfony2 Form ManyToOne实体类型


Symfony2 Form ManyToOne Entity-Type

这是实体

class MyEntity {
    /**
     * @var 'OtherEntity
     *
     * @ORM'ManyToOne(targetEntity="OtherEntity")
     * @ORM'JoinColumns({
     *   @ORM'JoinColumn(name="otherentity_id", referencedColumnName="id")
     * })
     */
    private $otherentity;
   // some other fields
}

我的控制器的操作:

someAction(Request $request) {
    $em = $this->getDoctrine()->getEntityManager();
    // simplified this step here with id=5, so that all Entities of class MyEntity a link to the OtherEntity with ID=5 
    $otherEntity = $this->getDoctrine()->getRepository('MyTestBundle:OtherEntity')->find(5);
    $myEntity = new MyEntity();
    $myEntity->setOtherEntity($otherEntity);
    $form = $this->createForm(new MyEntityType(), $myEntity);
    // do some form stuff like isValid, isMethod('POST') etc.
}

这是表单类型

class MyEntityType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);
        $builder->add('name', 'text');
        // HOW TO ADD THE ENTITY TO JOIN THE ADDED MyEntity with the OtherEntity (with ID=5)?
       // i tried this:
       ->add('otherentity', 'entity',
           array('class' => 'My'MyTestBundle'Entity'OtherEntity',
                  'read_only' => true,
                  'property' => 'id',
                  'query_builder' => function (
                'Doctrine'ORM'EntityRepository $repository) {
               return $repository->createQueryBuilder('o')
                           ->where('o.id = ?1')
                       ->setParameter(1, 5);
    }
)

)//。。。其他一些字段}//标准表格类型方法等。}

所以我的问题是,我必须为$builder->add选择什么来添加其他实体,所以如果我在控制器内执行$em->persist($myEntity),以通过表单持久化添加的myEntity,这样我的数据库中就有这样的记录:

id | name   | otherentity_id
1  | 'test' | 5

注意:我不想保留新的otherEntity,我只想创建一个新的MyEntity并添加otherEntity的外键。

难道不能像这样使用实体表单类型吗:

$builder->add('otherentity', 'entity', array(
    'class' => 'MyTestBundle:OtherEntity'
));