Symfony — встроенная форма не отображается

Я пытаюсь создать форму для вставки «вопросов», которые могут иметь один или несколько «ответов». Итак, я хочу добавить форму для встраивания объекта «Ответ».

Кажется, это работает, потому что я вижу форму вопроса, но внизу формы отображается только строка «Ответы», а не поля.

Вот мое действие контроллера:

public function addQuestionAction(Category $category)
{
    $question = new Question(); 
    $form = $this->createForm(new QuestionType(), $question);

    $request = $this->get('request');
    if ($request->getMethod() === 'POST') {
        $form->bind($request);

        $question->setCategory($category);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();          
            $em->persist($question);
            $em->flush();

        return $this->redirect($this->generateUrl('mycategory_questiondisplay',
            array('id' => $question->getId())));
        }
    }
    return $this->render('MyCategoryBundle:Question:add.html.twig',
        array(
            'form' => $form->createView(),
        )); 
}

Моя форма типа вопроса:

<?php

namespace My\CategoryBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class QuestionType extends AbstractType
{

     /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('description')
            ->add('answers', 'collection', array(
                   'type' => new AnswerType(),
                   'allow_add' => true)
            );

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Iel\CategoryBundle\Entity\Question'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'my_categorybundle_question';
    }
}

Мой объект вопроса:

<?php

namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Question
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="My\CategoryBundle\Entity\QuestionRepository")
 */
class Question
{
    /**
    * @ORM\OneToMany(targetEntity="My\CategoryBundle\Entity\Answer", 
mappedBy="question", cascade={"persist", "remove"})
    */
    private $answers;

    public function __construct()
    {
        $this->answers = new
    \Doctrine\Common\Collections\ArrayCollection();
    }

    public function addAnswer(\My\CategoryBundle\Entity\Answer
    $answer)
    {
        $this->answers[] = $answer;
            $answers->setQuestion($this);
            return $this;
    }

    public function removeAnswer(\My\CategoryBundle\Entity\Answer $answer)
    {
        $this->answers->removeElement($answer);
    }

    public function getAnswers()
    {
        return $this->answers;
    }

    public function setAnswers($answer)
    {
        $this->answer = $answer;

        return $this;
    }

    /**
    * @ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Category",
 inversedBy="question")
    * @ORM\JoinColumns({
    *  @ORM\JoinColumn(name="category_id", referencedColumnName="id")
    * })
    */
    private $category;
    /**
    * Set category
    *
    @param My\CategoryBundle\Entity\Category $category
    */
    public function setCategory(\My\CategoryBundle\Entity\Category $category)
    {
        $this->category = $category;
    }
    /**
    * Get category
    *
    @return My\CategoryBundle\Entity\Category
    */
    public function getCategory()
    {
        return $this->category;
    }

    /**
    * Remove categories
    **
    @param My\CategoryBundle\Entity\Category $categories
    */
    public function removeCategory(\My\CategoryBundle\Entity\Category $category)
    {
        $this->categories->removeElement($category);
    }

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titre
     *
     * @param string $titre
     * @return Question
     */
    public function setTitre($titre)
    {
        $this->titre = $titre;

        return $this;
    }

    /**
     * Get titre
     *
     * @return string 
     */
    public function getTitre()
    {
        return $this->titre;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Question
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }
}

И, наконец, объект ответа:

<?php

namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Answer
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="My\CategoryBundle\Entity\AnswerRepository")
 */
class Answer
{

    /**
    * @ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Question",
inversedBy="answer")
    * @ORM\JoinColumns({
    *  @ORM\JoinColumn(name="question_id", referencedColumnName="id")
    * })
    */
    private $question;
    /**
    * Set question
    *
    @param My\CategoryBundle\Entity\Question $question
    */
    public function setQuestion(\My\CategoryBundle\Entity\Question $question)
    {
        $this->question = $question;
    }
    /**
    * Get question
    *
    @return My\CategoryBundle\Entity\Question
    */
    public function getQuestion()
    {
        return $this->question;
    }

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="answer", type="text", nullable=true)
     */
    private $answer;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set answer
     *
     * @param string $answer
     * @return Answer
     */
    public function setAnswer($answer)
    {
        $this->answer = $answer;

        return $this;
    }

    /**
     * Get answer
     *
     * @return string 
     */
    public function getAnswer()
    {
        return $this->answer;
    }
}

Я действительно не могу найти, что не так в моей форме...


person Community    schedule 07.11.2013    source источник


Ответы (1)


Проблема в том, что на ваш вопрос пока нет ответов. Отсюда и отсутствие форм. Пытаться

$question = new Question();
$question->addAnswer(new Answer());

Это покажет пустую форму ответа.

Посмотрите кулинарную книгу, чтобы узнать, как использовать javascript для динамического добавления ответов из браузера.

person Cerad    schedule 07.11.2013
comment
О, это может быть точкой. Если я добавлю его, он вернет мне ошибку FatalErrorException: Error: Class 'My\CategoryBundle\Controller\Answer' не найден в /My/CategoryBundle/Controller/CategortController.php, строка 275. У меня нет AnswerController... - person ; 07.11.2013
comment
Я поставил его в неправильном месте. Теперь он возвращает мне форму, как и раньше, с единственной строкой Ответ. - person ; 07.11.2013
comment
Тогда, может быть, ваш шаблон не показывает form.answers? В противном случае проработайте пример из поваренной книги. - person Cerad; 07.11.2013