eav
eav

Reputation: 2171

Symfony2 Form ManyToOne Entity-Type

This is the entity:

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

   // some other fields
}

My Controller's action:

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

This is the 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);
    }
)

) // ... some other fields } // standard formtype methods etc. }

So my question is, what do I have to choose for $builder->add for adding the otherEntity, so if I do a $em->persist($myEntity) inside the controller to persist the added myEntity through the form, so that i have a record like this in my database:

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

Note: I don't want to persist a new otherEntity, I just want to create a new MyEntity and add the foreign-key of an OtherEntity.

Upvotes: 1

Views: 3798

Answers (1)

Jan-Henk
Jan-Henk

Reputation: 4874

Can't you just use the Entity form type like this:

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

Upvotes: 6

Related Questions