How to embed form in symfony2 for entity ManyToOne relation?

rahul tripathi picture rahul tripathi · Jul 5, 2012 · Viewed 8.9k times · Source

I'm quite new to Symfony 2 Framework.I want to form embed for entity ManyToOne relation .I have to entity Address and AddressType

Address entity

namespace Webmuch\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

class Address
{

    private $id;
    private $line1;
    private $city;
    private $zip;
    private $phone;

    /**
     * @var string $type
     *
     * @ORM\ManyToOne(targetEntity="AddressType")
     * @ORM\JoinColumn(name="address_type_id", referencedColumnName="id")
     */
    private $type;
}

AddressType Entity

namespace Webmuch\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

class AddressType
{
    private $id;
    private $title;
}

Address Controller

namespace Webmuch\ProductBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Webmuch\ProductBundle\Entity\Address;
use Webmuch\ProductBundle\Form\AddressType;

/**
 * Address controller.
 *
 * @Route("/address")
 */
class AddressController extends Controller
{
    /**
     * Displays a form to create a new Address entity.
     *
     * @Route("/new", name="address_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Address();
        $form   = $this->createForm(new AddressType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }
}

Form Section

namespace Webmuch\ProductBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class AddressType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('line1')
            ->add('line2')
            ->add('state')
            ->add('city')
            ->add('zip')
            ->add('phone')
            ->add('type')
        ;
    }
}

I've spent the whole day stuck with this and I have tried a lot of things but I couldn't manage get it working.

Answer

meze picture meze · Jul 5, 2012

It's covered in the documentation.

You create one more form type for AddressType (called AddressTypeType? Ugly, but you chose the name) and replace ->add('type') with ->add('type', new AddressTypeType());.