I am repeating something similar to the code below in my app several times for various schemas and collections, so it’s violating the DRY principle. Is there a better way to do upsert in Autoform?
Thank you for the code snippet. I was just wondering whether I am doing the right thing - surely I am not the only one who needs to upsert? Seems like a common scenario.
Change the type attribute’s value to “insert” or “update” as appropriate, probably by updating a reactive variable.
Change the doc attribute’s value to the correct document for an update or to null (or a document containing default values) for an insert, probably by updating a reactive variable.
Call AutoForm.resetForm(formId). This will clear any existing validation errors for the form.
Set your formType as either a reactive-var (better) or Session variable with a default value of “insert”
Template.schedule.onCreated(function(){
this.formType = new ReactiveVar( 'insert' );
});
Next, set up helpers for both the current doc and formType. This checks for a current document, and if it exists, updates the form to an “update” type and provides the document to update. The formType helper just fetches the current formType value.
Template.schedule.helpers({
currentSchedule: function() {
var currentSchedule = Schedules.findOne({ campaignId: FlowRouter.getParam('campaignId') });
if (currentSchedule) {
Template.instance().formType.set('update');
return currentSchedule;
}
},
formType: function() {
var formType = Template.instance().formType.get();
return formType;
}
});