Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor dynamic form generation

Tags:

meteor

I have a survey form I would like an admin to be able to add more questions to on the fly. The way I'm thinking of doing this is to have the admin add questions to a Questions collection with several properties e.g:

{
    "description" : "desc",
    "fieldType" : "textField",
    "sortOrder" : 1,
    "dataType" : "text",
    "_id" : "eFopP8XFgY8Br93fA"
}

and then on the client side, loop through these using an #each block and a dynamic template like so:

{{#each questions}}
  {{>Template.dynamic template=fieldType}}
{{/each}}

Now the "fieldType" field would correspond to the name of a stored template e.g

<template name="textField">
    <div>
        <input id="{{_id}}" type="{{dataType}}" class="validate">
        <label for="{{_id}}">{{description}}</label>
    </div>
</template>

and inside these templates would have different input fields depending on the type.

I have two issues:

  1. Is this a good way to go about this problem?
  2. If it is, how would you be able to get the values of these input fields when saving the answers (as we don't know what fields could be there at compile time)
like image 360
Jon Avatar asked Sep 02 '26 15:09

Jon


1 Answers

Regarding your first question, I agree with @Kyll regarding autoform and I think you can pass the schema as a json object dynamically.

Regarding your 2nd question, please check SO question Dynamically add form fields in meteorjs where you will find answer to your second question. You can easily grab value of all fields in your dynamically created form using .serializeArray() JQuery serializeArray

like image 102
Mahmoud Metwally Avatar answered Sep 05 '26 13:09

Mahmoud Metwally