Symfony - How to save foreign key in form "many-to-one"

user2094540 picture user2094540 · Oct 31, 2013 · Viewed 7.2k times · Source

I'm new to Symfony 2 and I'm trying to build a form for a content type that has a foreign key. I have no idea about how to save the foreign key using the form.

My two tables are "Category" and "Question". A question belongs to one category (many-to-one). So my Question.php file in Entity contains :

<?php

namespace Iel\CategorieBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Question
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Iel\CategorieBundle\Entity\QuestionRepository")
 */
class Question
{
    /**
    * @ORM\ManyToOne(targetEntity="Iel\CategorieBundle\Entity\Categorie")
    * @ORM\JoinColumn(nullable=false)
    */
    private $categorie;
    /**
    * Set categorie
    *
    @param Iel\CategorieBundle\Entity\Categorie $categorie
    */
    public function setCategorie(\Iel\CategorieBundle\Entity\Categorie $categorie)
    {
        $this->categorie = $categorie;
    }
    /**
    * Get categorie
    *
    @return Iel\CategorieBundle\Entity\Categorie
    */
    public function getCategorie()
    {
        return $this->categorie;
    }

I've tryed build the controller function like this, but it's not a right syntax :

public function addquestionAction()
{
    $question = new Question;

    $form = $this->createFormBuilder($question)
        ->add('titre', 'text')
        ->add('auteur', 'text')
        ->add('contenu', 'textarea')
        ->add('category_id', $this->getCategorie())    
        ->getForm();    

    $request = $this->get('request');

I don't know how to write the current category_id in the Question's table using this form.

Answer

medowlock picture medowlock · Mar 22, 2014

Better way would be to declare "categorie" of type "entity". Something like this:

$form = $this->createFormBuilder($question)
    ->add('titre', 'text')
    ->add('auteur', 'text')
    ->add('contenu', 'textarea')
    ->add('category', 'entity', array(
        'class' => 'IelCategorieBundle:Categorie',
        'property' => 'name',
    ))
    ->getForm();

This should create a select where the option value is the category id and the option display value is the category name. Persisting the $question object will insert the category id in the foreign key field from the "questions" table.