Symfony2 has wonderful documentation about embedded forms. Embedded forms tutorial is created based on OneToMany relationship entities. I noticed everyone or even myself blindly followed the tutorial without considering what relationship we are using between entities. But OneToOne relationship embedded forms are easy to work. It’s anyway answered in many forums, still people getting confused. So let’s try to make in clear from below example.
Page Entity
/** * @ORM\Entity * @ORM\Table(name="Page") * @ORM\Entity(repositoryClass="PageRepository") */ class Page { // All your fields here /** @ORM\OneToOne(targetEntity="Seo", mappedBy="page", cascade={"persist", "merge"}) */ protected $seo; public function __construct() { } }
Seo Entity
/** * @ORM\Entity * @ORM\Table(name="seo") * @ORM\Entity(repositoryClass="SeoRepository") */ class Seo { // All your fields here /** * @ORM\OneToOne(targetEntity="Page", inversedBy="seo") * @ORM\JoinColumn(name="page_id",referencedColumnName="id") * */ protected $page; public function __construct() { } }
Now, Once you created the forms and controllers. Open your PageType.php. Now start customization your form.
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('description') ->add('status', 'choice', array( 'choices' => array('draft' => 'Draft', 'publish' => 'Publish'), 'required' => true, 'empty_value' => 'Choose status', )); $builder->add('seo',new SeoType()); // add this field to embed the seo form fields }
Now start modifying the page controller.
/** * Displays a form to create a new Page entity. * */ public function newAction() { $entity = new Page(); $entity->setSeo(new Seo()); // embed seo entity here $form = $this->createForm(new PageType(), $entity); //.... your normal code goes here }
Okay cool, Now check the browser, Hope you got working, Cheers!
I think you made a typo :
$entity->getSeo(new Seo());
should be :
$entity->setSeo(new Seo());
Otherwise, thanks for the blog post 😉
Thankyou Sylvain for notifying it, just updated it.
private function updateAction() is missed in this example I think ;))