1

这是实体

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

   // some other fields
}

我的Controller的操作:

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 选择什么来添加 otherEntity,所以如果我$em->persist($myEntity)在控制器内部执行一个操作以通过表单持久保存添加的 myEntity,这样我的数据库中就会有这样的记录:

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

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

4

1 回答 1

6

你不能像这样使用实体表单类型

$builder->add('otherentity', 'entity', array(
    'class' => 'MyTestBundle:OtherEntity'
));
于 2013-05-14T21:45:59.747 回答