One To One Relationship embedded forms

on with 3 Replies

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!

Posted in Symfony2 and tagged , by .

About Gowri

I am professional web developer with 4+ years experience. PHP, jQuery, WordPress, Magento and Symfony2 are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.

3 thoughts on “One To One Relationship embedded forms

Leave a Reply to Valery Cancel reply

Your email address will not be published. Required fields are marked *