Search code examples
javascriptnode.jsformsmeteormeteor-autoform

Show form when clicking edit on profile page in Meteor


On many pages, I can see my user profile page and click a link to edit some information on my profile page. For instance, on Facebook I can see information about myself on the About page, and if I click edit, the small section changes to form inputs.

How can I best achieve same behaviour using meteor-autoform?

I can use

{{> quickForm id=id collection=collection fields="firstName,middleName,lastName"}}

to show the form.

But how can I initially hide the form and first show it when the user clicks edit? If I have 4 sections each with some information and a separate form (full name, birthday, education, work experience), should I then print 4 forms with meteor-autoform inside a <div style="display:none"> element and when the user clicks edit, the div with information hides and the form is shown, and vice versa?

I guess it can be done more smooth, only rendering the forms if the user clicks edit. I just don't how to do this neatly.


Solution

  • The "meteor way" would be to use a reactive helper, which depends on a reactive value:

    Template.profile.helpers({
      showProfileForm: function () {
        return Session.get('showProfileForm');
      }
    });
    

    Then in your template, instead of an ugly display: none you will use Handlebars:

    {{#if showProfileForm}}
      {{> quickForm id=id collection=collection fields="firstName,middleName,lastName"}}
    {{/if}}
    

    From there, you can just change the state of your showProfileForm session variable (in an event function for example), and your helper will change its return value reactively:

    Template.profile.onCreated(function () {
      Session.set('showProfileForm', false); // to avoid undefined at first
    });
    
    Template.profile.events({
      'click a#showHideForm': function(e, template) {
        Session.set('showProfileForm', !Session.get('showProfileForm'));
      }
    });
    

    If you dislike using the Session for this, David Weldon wrote a nice piece about how to use reactive variables instead of Session variables for helpers like this one.