Pregunta

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.

¿Fue útil?

Solución 2

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top