0

I have a form submitting a quizz to a user, and according to their answers I may want to ask them additionnal questions that I would have to dynamically add to said form.

What I have been doing so far is that I have stripped the questions that needs to be triggered by user answers (identified by a 'triggerQuestionId' attribute containing the id of the question that needs to be answered for them to be displayed) out of the questions list of the quizz, created a form and sent it to my view in twig to display the original questions to the user like so :

    <table>
        <tbody id="table_body">
            {% for answer in form.answers %}
                    <tr id={{ answer.vars.value.question.id }}>
                        <td><span class="question">{{ answer.vars.value.question.title }}</span></td>               
                        <td class="answer">
                            {{ form_widget(answer.choice) }}
                        </td>
                    </tr>                  
            {% endfor %}
        </tbody>
    </table>
    {{ form_rest(form) }}

I use an Ajax request to check if any question should be displayed when the user selects an answer to a question, and if so I create a new tr element similar to the above for the triggered question and add it to the table.

However, after posting the form, I (logically) get the following error : "ERROR: This form should not contain extra fields."

So I figured I would originally load every question and only display in the view those with 'triggerQuestionId' set at null.

But that isn't working either because if I keep {{ form_rest(form) }} in, the triggered questions are displayed, and if I don't I get an error saying that the CSRF token is invalid.

I am still a newbie regarding Symfony and I feel like there must be a much easier way that I don't know or haven't thought about.

I hope I have made myself clear enough, but do not hesitate to ask for precisions if needed.

Thanks in advance

2
  • Start by manually including the CSRF token in your form with {{ form_row(_token) }} and you won't have to use {{ form_rest(form) }} anymore Commented Jun 6, 2013 at 14:13
  • I tried but then it showed the Extra Fields error anyway. But thanks for the tip, it may come in handy someday ! Commented Jun 6, 2013 at 15:29

1 Answer 1

1

Look into the collection Field Type.

There you find and example to dynamically add fields to an existing form via jQuery.

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

1 Comment

It was the kind of solution I was hoping for. Thanks a lot !

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.