如何在symfony2中为实体ManyToOne关系嵌入表单?

时间:2012-07-05 10:26:05

标签: php symfony doctrine symfony-forms many-to-one

我对Symfony 2 Framework很新。我想为实体 ManyToOne 关系构建嵌入。我必须实体地址 AddressType

地址实体

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实体

namespace Webmuch\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

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

地址控制器

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()
        );
    }
}

表单部分

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')
        ;
    }
}

我花了整整一天时间坚持这一点,我尝试了很多东西,但是我无法管理让它发挥作用。

1 个答案:

答案 0 :(得分:6)

它涵盖在documentation

您为AddressType创建了另一种表单类型(名为AddressTypeType?丑陋,但您选择了名称)并将->add('type')替换为->add('type', new AddressTypeType());