Question

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

Was it helpful?

Solution

Look into the collection Field Type.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top