Symfony form build with radios

In Symfony I have two entities which are related to each other: Question and Answer. The relation is One to Many(one question can have many answers). Using thees entities I am trying to build a from for a quiz that will display a question and four answers as radio buttons. Using a query I am retrieving the data from that database. The object contains data for a question and answers in an array collection. The question data will be passed as a normal variable to the twig template, but the answers need to be build in a form as radio buttons. At the moment I managed to build the answers as text fields but I need them as radio buttons so the user can choose one answer for the question. I have read in the documentation I need to use maybe ChoiceType, and to get the radios I need to use multiple => true, expanded => false but after many hours of trying I still can’t get them right. Would appreciate if someone could give me a hand with this as I have been struggling for a while. Here is my code for my entities, controller code, and the code for building the form and some screenshots of the object from the query and what I have now in the view.

Entity: Question

/**
 * Question
 *
 * @ORM\Table(name="question")
 * @ORM\Entity(repositoryClass="QuizBundle\Repository\QuestionRepository")
 */
class Question
{
    /**
     * @ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private $answers;
    public function __construct()
    {
        $this->answers = new ArrayCollection();
    }

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

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

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

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * Add answer
     *
     * @param \QuizBundle\Entity\Answer $answer
     *
     * @return Question
     */
    public function addAnswer(\QuizBundle\Entity\Answer $answer)
    {
        $this->answers[] = $answer;
        return $this;
    }

    /**
     * Remove answer
     *
     * @param \QuizBundle\Entity\Answer $answer
     */
    public function removeAnswer(\QuizBundle\Entity\Answer $answer)
    {
        $this->answers->removeElement($answer);
    }
    /**
     * Get answers
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAnswers()
    {
        return $this->answers;
    }
}

Entity: Answer

/**
 * Answer
 *
 * @ORM\Table(name="answer")
 * @ORM\Entity(repositoryClass="QuizBundle\Repository\AnswerRepository")
 */
class Answer
{
    /**
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="answers")
     * @ORM\JoinColumn(name="question_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $question;

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

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

    /**
     * @var bool
     *
     * @ORM\Column(name="isCorrect", type="boolean")
     */
    private $isCorrect;

    /**
     * Get id
     *
     * @return int
     */
    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;
    }

    /**
     * Set isCorrect
     *
     * @param boolean $isCorrect
     *
     * @return Answer
     */
    public function setIsCorrect($isCorrect)
    {
        $this->isCorrect = $isCorrect;

        return $this;
    }

    /**
     * Get isCorrect
     *
     * @return bool
     */
    public function getIsCorrect()
    {
        return $this->isCorrect;
    }

    /**
     * Set question
     *
     * @param \QuizBundle\Entity\Question $question
     *
     * @return Answer
     */
    public function setQuestion(\QuizBundle\Entity\Question $question = null)
    {
        $this->question = $question;
        return $this;
    }
    /**
     * Get question
     * @return \QuizBundle\Entity\Question
     */
    public function getQuestion()
    {
        return $this->question;
    }
}

Form QuizFormType where answers is a collection type:

class QuizFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('answers', CollectionType::class, array('entry_type' => QuizAnswerFormType::class,));
        $builder->add('Submit',SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'QuizBundle\Entity\Question'));
    }

    public function getName()
    {
        return 'quiz_bundle_quiz_form_type';
    }
}

Form QuizAnswerFormType

class QuizAnswerFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('answer');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'QuizBundle\Entity\Answer'));
    }

    public function getName()
    {
        return 'quiz_bundle_quiz_answer_form_type';
    }
}

Code in the Controller:

public function showAction(Request $request)
    {

        $id = $this->random();
        $question = $this->getDoctrine()->getRepository('QuizBundle:Question')->findOneByIdJoinedToCategory($id);

at this point $question is an object containing the question data and answers like in the screenshot. $q_question and $q_image are just passed to the view as normal variables.

        $q_question = $question->getQuestion();
        $q_image = $question->getImage();

passing the object to the QuizFormType

        $form = $this->createForm(QuizFormType::class, $question);

        $form->handleRequest($request);
        if($form->isSubmitted()&& $form->isValid()) {
          $formData = $form->getData();

        return $this->render('QuizBundle:Default:addTest.html.twig', array('test' => $formData));
        }
    return $this->render('QuizBundle:Default:playQuiz.html.twig', array('form' => $form->createView(),'question' => $q_question, 'image' => $q_image, 'obj' => $question));

}

Screenshot of the object:

This is my display using this code:

An interesting example pitting stack overflow directly against sitepoint. Which one will actually help the poster?

If it’s simple PHP then posting on one of them is enough as I seem to get some help, but because it’s Symfony less people seem to know or try to suggest.

I glanced at your stackoverflow question but my eyes quickly glazed over at the sheer length of your post. Indicates sort of a random approach to problem solving. Plus there has been so many of these question/answer posts recently that I kind of question the source.

Start over, make yourself a simple form with check boxes (or if you really expect that a question can have multiple correct answers then use radio boxes. Once you understand the basics then you should be able to trouble shoot and see what is happening. Or at least narrow down the problem.

Of course there are plenty of people much smarter than I am who might be able to glance at the question and immediately see the problem.

I see one brave soul has tried to do just that but it is clearly not going well. Hint: when someone asks for more info (like Symfony version) you might consider providing it.

I find the Symfony form component to be one of the most complicated things so far.
The length of the post is because of the code for the entities and it is just so people can see the relation between the entities and the properties of each entities.
The form code I realised is not necessary, and I should build the form in the controller and not in classes of their own. This is because I just need the answers to be build in the form but not the question data. Also the question form doesn’t need to include the answer form. There is nothing in the question form as data is passed straight to twig, and the answers are build in the controller. Regarding the Symfony version I forget to answer, but the query builder seems to give some results so far.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.