Как встроить форму в symfony2 для отношения сущности ManyToOne?
Я довольно новичок в Symfony 2 Framework. Я хочу сформировать вставку для сущности отношения ManyToOne. Я должен к сущности Address и 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 Entity
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 ответ
Это описано в документации.
Вы создаете еще один тип формы для AddressType (называемый AddressTypeType? Ужасно, но вы выбрали имя) и заменяете ->add('type')
с ->add('type', new AddressTypeType());
,