简体   繁体   中英

Symfony 2 dynamically add field to form on user site

I am working on survey bundle. The goal is to provide user a fully working survey system. I have already prepared a backend which allows you to create survey, add questions (open text, radio buttons, checkboxes), make questions required or not, activate survey, generate tokens and send link to the survey with token on email. Of course i also have frontend which shows survey and saves answers. Now i want to add another possibility. A question with answers (radio or checkbox) and comment. For example:

Do you have a dog?

  • Yes
  • No

If user select Yes then additional field with question "What is the dog's name?" should appeared and allow user to enter dogs name. If user select No then nothing happen.

Such simple question can be with hidden field but what if i will have 20 questions with such "additional" informations?

Do you know some mechanism in symfony which will allow me to do that? I was trying with listeners but could not create anything flexible and universal (I can have questions with checkboxes and some of those answer in one question can have additional fields other dont have to).

I have a feeling you can't do this only a FormType and form event listeners. If your goal is to show/hide the additional questions based on the choice of the user within the same form, you will need to involve some javascript as well. The FormType generates only the form fields (and any embedded/nested forms as well). All other UI interaction or dynamic validation should be made using JavaScript and FormEvent listeners.

What I would do is to have an event listener which adds an attribute (ie data-has-additional ) to all question radio/checkboxes (which have additional questions/fields). Then I would have a jquery on() listener which checks if the radio/checkbox is selected/deselected and based on the status it would show/hide the additional fields. You should be able to abstract this and make it a generic javascript which works for all "additional questions".

Then I would create event listeners to check if the submitted form is valid (ie if you have an additional question which requires some text to be inserted and so on).

Another way might be to research some of the "multi-step form bundles". Some of them might have a similar option already implemented and that might help you in your development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM