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.
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.
Try categorie instead of category_id. Doctrine and SF2 Forms work with associations, not with foreign keys.
Also $this->getCategorie() won't work. You're in the controller context. 
Instead of this leave the form to guess the type based on the Question mapping file.
/* ... */
$form = $this->createFormBuilder($question)
    ->add('titre', 'text')
    ->add('auteur', 'text')
    ->add('contenu', 'textarea')
    ->add('categorie', null)    
    ->getForm(); 
/* ... */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With