Symfony2表单ManyToOne实体类型

eav*_*eav 1 php symfony

这是实体:

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

   // some other fields
}
Run Code Online (Sandbox Code Playgroud)

我的财务主管的行动:

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.
}
Run Code Online (Sandbox Code Playgroud)

这是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);
    }
)
Run Code Online (Sandbox Code Playgroud)

)// ...其他一些领域} //标准表格类型方法等}

所以我的问题是,我有什么选择$ builder-> add来添加otherEntity,所以如果我$em->persist($myEntity)在控制器内执行以通过表单保留添加的myEntity,那么我在我的数据库中有这样的记录:

id | name   | otherentity_id
1  | 'test' | 5
Run Code Online (Sandbox Code Playgroud)

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

Jan*_*enk 6

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

$builder->add('otherentity', 'entity', array(
    'class' => 'MyTestBundle:OtherEntity'
));
Run Code Online (Sandbox Code Playgroud)