Otonel Otonel - 5 months ago 55
PHP Question

Symfony form submits wrong data

In Symfony I have this part of my code where I am building a view with some data and a form with some radio buttons. When submitting the form I am doing a dump in the view to check which data has been submitted, but the data does not match with the one the form was build. Can someone help? Thanks.

public function playAction(Request $request){
$data = $this->getDbQuestion();
$questionData = $data[0];
dump($questionData);
$answerData = $data[1];
dump($answerData);

$form = $this->createFormBuilder($answerData)
->add('answers', ChoiceType::class,
array(
'choices'=> $answerData,
'multiple'=>false,'expanded'=>true,
'choice_label' => 'answer',
))
->add('Submit',SubmitType::class, array('label' => 'Send Answer'))
->getForm();

$form->handleRequest($request);
if($form->isSubmitted()) {
$formData = $form->getData();
return $this->render('QuizViews/correctAnswer.html.twig', array(
'ss' => $formData
));
}
return $this->render('QuizViews/playQuiz.html.twig', array(
'form' => $form->createView(),
'question' => $questionData
));
}



Twig


<a href="/quiz/question">
<input type="button" value="Start Quiz" />
</a>
<br>
FormData Correct {{ dump(ss) }}


Form data

Submitted form Data

Answer

After chatting, this might be a better solution for the answer section:

->add('answers', EntityType::class, array(
    'class' => 'AppBundle:Answer',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('a')
                ->where('a.question_id->getId() = :qID')
                ->setParameter('qID', 1);
    },
     'multiple'=>false,
     'expanded'=>true,
    'choice_label' => 'answer',
))

Try it!