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.
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();
/* ... */