1

In Symfony I am building a form with four possible choices as radio buttons. When the user submits the form with a choice, I am taking the submitted form data (the user choice) and display it in twig. The problem is that sometimes the submitted form data is null even if the user selected a radio, and sometimes the selected choice is passed and displayed in twig. Also sometimes after reciving null in twig and refreshing the page the data is shown, but this doesn't always happen. Why this inconsistency? How can I solve this? Thanks

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

        dump($questionData);
        $answerData = $data[1];
        dump($answerData);

        $form = $this->createFormBuilder($answerData)
            ->add('answers', EntityType::class, array(
                'class' => 'QuizBundle:Answer',
                'query_builder' => function (EntityRepository $er) use ($questionID) {
                    return $er->createQueryBuilder('a')
                        ->where('a.question = :qID')
                        ->setParameter('qID', $questionID);
                },
                'multiple'=>false,
                'expanded'=>true,
                'error_bubbling' => true,
                'choice_label' => 'answer',
            ))
        ->add('Submit',SubmitType::class, array('label' => 'Send Answer'))
        ->getForm();

        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()) {
            $formData = $form->get('answers')->getData();
            $errors = $form->getErrors();
            return $this->render('QuizViews/correctAnswer.html.twig', array('ss' => $formData, 'errors' => $errors ));
        }

        return $this->render('QuizViews/playQuiz.html.twig', array('form' => $form->createView(),'question' => $questionData));
    }

Dumping the submitted form data in twig

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

The form data

Null in twig

User answer in twig

Adding $form->isValid()I get this in twig when the answer is not submitted.

Adding validation to form, in twig I get this

1
  • Hi there Otonel. You are very close. Don't get frustrated. Try to add more debug or dump statements to figure out what might be wrong. Commented Jun 28, 2016 at 15:05

2 Answers 2

1

Glad you got further. I believe that the "$formData" is coming back as an answer object, and all you have to do in twig is call something like:

{{ ss.getAnswer }}

Where getAnswer is a method for the Entity Answer (I don't remember your code). The form data correct you show above looks exactly like a dump of an "object". Remember you need to think in terms of objects.

Let me know if that doesn't work.

Edit #2.

Try this change:

->add('answers', EntityType::class, array(
        'class' => 'QuizBundle:Answer',
        'query_builder' => function (EntityRepository $er) use ($questionID) {
          return $er->createQueryBuilder('a')
                ->where('a.question = :qID')
                ->setParameter('qID', $questionID);
        },
        'multiple'=>false,
        'expanded'=>true,
        'choice_value' => 'answer',
        'choice_label' => 'answer',
))

Where I've added 'choice_value' => 'answer', in this case 'answer' should be the answer value stored in the Answer Entity.

Edit #3. This is weird. I'm not sure why it's not working. You shouldn't need to pass in the $answerData into the builder. Try leaving it blank, and let's change it to a drop-down list (default):

$form = $this->createFormBuilder()
    ->add('answers', EntityType::class, array(
         'class' => 'QuizBundle:Answer',
         'label' => 'Select an Answer',
         'choice_value' => 'answer',
         'choice_label' => 'answer',
    ))

If that doesn't work, something else is definitely wrong, possibly your Entities. This returns the Entity value in the db for me.

Sign up to request clarification or add additional context in comments.

6 Comments

Hi. I tried to call my getAnswer() from my entity with no success. I don't get any suggested methods after the dot. (ss.) Also i tried $formData = $form->get('answers')->getData(); $f = $formData->getAnswer(); but I get this error: Error: Call to a member function getAnswer() on a non-object
Did you create getters & setters in Symfony for Answer: php bin/console doctrine:generate:entities AppBundle/Entity/Answer ??? This automatically creates them, then you can open Answers.php to see what changes are made. It stores a backup to the file "Answers.php~".
I already had getters and setters in my Answer entity. I did that command in the console anyway.
It's the twig file "QuizViews/correctAnswer.html.twig" that needs to contain {{ ss.getAnswer }} because you are passing the object ss to the twig file in the array. Alternately you could pass the answer in the array like so: array('ss' => $formData, 'answer' => $formData->getAnswer()), and then in your twig you could print it out like so: {{ answer }}.
I tried in the twig {{ss.getAnswer}} and also before sending the data to twig in the controller, but apparentlly $formData is not an object (the error in the above comment)
|
1

Did you tryed to check if your form was valid?

if($form->isSubmitted() && $form->isValid()) {

Also, set and display form errors may help a lot, to check what is wrong, and which part of your form isn't correct.

4 Comments

I have added $form->isValid() and now when submitting the answer, the controller is trying to build the question again. So my form is not valid..
I have added in my code to get form errors and display it in twig. When submitting the answer and the question is built again in twig, there are no errors dumped. Only when the choice is submitted and the choice is displayed in twig correctly, then the form shows no errors.
@Alvin Bunk. I have edited the code and now I have the drop down list. The good new is that the selected answer is displayed in twig correctly every time. The only problem is that the list contains all the answers from my database for all the questions.
@Alvin Bunk I have tried the code in edit #3 and it works fine with the drop down menu, but why it doesn't work with the radio buttons?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.