Creating conditional forms based on input


#1

Let’s say I have a form to order two different types of products.

Product #1 only has one option to choose from, product #2 has two options to choose from etc.

Each product gets it’s on specifications that can/need to be set in the database based on which product has been chosen. How would one go about creating a conditional form that always shows the form fields needed AND creates a corresponding document once the form gets submitted? This is something that should be done automatically I guess?


#2

You can use a reactive variable like Session, ReactiveDict or ReactiveVar to set a state (do this from a button click event or whatever you want):

Session.set('productType', 1);

Then use helpers for your template logic:

Template.foo.helpers({
    productTypeIs: function (prod_type) {
        return Session.get('productType');
    }
});
<template name="foo">
    {{#if productTypeIs 1}}
        <!-- product type 1 form -->
    {{/if}}
    {{#if productTypeIs 2}}
        <!-- product type 2 form -->
    {{/if}}
</template>

#3

Is this really how it should be done? Basically I will have to hard code each form and whenever something changes with certain conditions/fields I will have to create more and more sessions. Let’s say form 1 has two form fields that again hide other form fields based on what’s selected. That’ll be overkill, won’t it?


#4

well, I would just hint that there is such thing as autoform which show fields based on schema.