Jon
Jon

Reputation: 493

Meteor dynamic form generation

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)

Upvotes: 3

Views: 1806

Answers (1)

Mahmoud Metwally
Mahmoud Metwally

Reputation: 990

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

Upvotes: 3

Related Questions