Search code examples
javascriptmeteormeteoritemeteor-blazemeteor-helper

Passing Collection ID to generate Forms in Meteor


I've a collection "Country" which displays a list of countries and their info. A book option leads a user to the "Activity" form which has dropdown fields like To,From. How do I pass the "Country" ID so that the form fields in "Activity" belong to the "Country" whose Book button the user has clicked. I think I should use a reactive var to store the country id and then perform operations to change the form fields accordingly. I'm fairly new to this and a heads up to the approach would be deeply appreciated.

The submit code for activity collection is :

    Template.activitySubmit.onRendered(function () {
    if (Session.get("submit-bypass") === true) {
        Session.set("submit-bypass", false);
        window.history.back();
    }

    $("#activity-goal").material_select();
});

Template.activitySubmit.events({
    "submit form": function (e) {
        e.preventDefault();

        var title = $(e.target).find("#activity-title").val()
        if (title.length === 0) {
            throwError("You must have a title.");
            $("activity-title").focus();
            return;
        }

        var activty = {
            title: title,
            goal: parseInt($(e.target).find("#activity-goal").val())
        };

        Meteor.call("activityInsert", activty, function (error, result) {
            if (error) {
                throwError(error.reason);
                return;
            }

            Session.set("submit-bypass", true);
            Router.go("activityPage", { _id: result._id });
        });
    }
});

Solution

  • This is how you should use reactive var package

    1. Add the package to your project, in terminal meteor add reactive-var
    2. Open your JS file for the template, like activitySubmit.js
    3. Declare reactive var like so Template.activitySubmit.onRendered(function () { this.selectedCountry = new ReactiveVar(null); });
    4. Then update the reactive var as needed and use it

    `

    Template.activitySubmit.events({
          'change #country': function(e){
             var country = $(e.target).val()
             var instance = Template.instance();
             instance.selectedCountry.set(country);
          },
    
    
      'submit form': function (e) {
         ....
          var instance = Template.instance();
          var country = instance.selectedCountry.get(country);
         ....
      }
    
    });`
    
    1. If you'd like to pass the data around across mulitple files (globally), you can simply use Session. Session.set('myId', id) and Session.get('myId')