2013-05-14 72 views
1

這是實體Symfony2的形式多對一實體類型

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. 
} 

這是Formtype

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

) // ...一些其他領域 } // 標準formtype方法等 }

所以我的問題是,我有什麼選擇適合$ builder->添加用於添加otherEntity,所以如果我做一個$em->persist($myEntity)控制器內堅持通過形式加入myEntity所,讓我在我的數據庫這樣的記錄:

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

:我不想堅持新otherEntity ,我只想創建一個新的MyEntity並添加OtherEntity的外鍵。

回答

6

你就不能使用Entity form type這樣的:

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

我認爲這會做的伎倆,但我得到那麼「實體傳遞給選擇字段必須進行管理,也許他們堅持在實體經理「 – eav

+0

你可以顯示你傳遞給表單生成器的選項嗎? –

+0

我編輯了我的問題。你可以找到上面的選項。 (我也在沒有QueryBuilder的情況下試過了。) – eav