Symfony2表单ManyToOne实体类型

时间:2013-05-14 21:10:26

标签: php symfony

这是实体

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->添加添加其他实体的添加,所以如果我在控制器中执行$em->persist($myEntity)以通过表单保留添加的myEntity,那么我在我的数据库中有这样的记录:

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

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

1 个答案:

答案 0 :(得分:6)

你不能像这样使用Entity form type

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