Submit url parameter with form to meteor method - javascript

I am using aldeed:autoform in order to render a form and run its result through a Meteor.method(). My form looks as follows:
SelectPlanTemplates = new SimpleSchema({
templates: {
type: [String],
autoform: {
options: function() {
return PlanTemplates.find().map(function(doc) {
return { label: doc.title, value: doc._id };
});
},
noselect: true
}
},
userId: {
type: String,
allowedValues: function() {
return Meteor.users.find().map(function(doc) {
return doc._id;
});
},
autoform: {
omit: true
}
}
});
On my template, I just do the following.
+ionContent
+quickForm(schema="SelectPlanTemplates" id="SelectPlanTemplatesForm" type="method" meteormethod="createPlanFromTemplates")
My url is constructed like /plan/from_templates/{:userId}. I tried creating a hook to add the user id before submitting it.
AutoForm.hooks({
SelectPlanTemplatesForm: {
before: {
method: function(doc) {
doc.userId = Router.current().params.userId;
return doc;
}
}
}
});
However, it never seems to get to this hook.
How would I take a route parameter and pass it with my form to a meteor method with auto form?

I think I figured out a little bit of a weird way of do it.
In the router:
this.route('selectPlans', {
waitOn: function() {
return Meteor.subscribe('plan_templates');
},
path: '/select/plan_templates/:_id',
template: 'selectTemplates',
data: function() {
return new selectPlanTemplates({ userId: this.params._id });
}
});
Then I added doc=this to my template

Related

Issues with dynamic routing using meteor-autoform and iron:router

What I am trying to do is create a form with meteor-autoform that will redirect the user to a newly generated route on submit. My thought process is that I can take the submissions _id and use it for an iron:router parameter. What I have so far looks as followed:
Creation of Form
Submits = new Meteor.Collection('Submits');
Submits.allow({
insert: function(username, doc){
return !!username;
}
});
SubmitSchema = new SimpleSchema({
title: {
type: String,
label: "Title"
},
subject:{
type: String,
label: "Subject"
},
summary:{
type: String,
label: "Summary"
},
author:{
type: String,
label: "Author",
autoValue: function() {
return this.userId
},
autoform: {
type: "hidden"
}
},
createdAt: {
type: Date,
label: "Created At",
autoValue: function(){
return new Date()
},
autoform: {
type: "hidden"
}
}
});
Submits.attachSchema( SubmitSchema );
Routing
Router.route('/submit', {
layoutTemplate: 'submitLayout',
waitOn: function() { return Meteor.subscribe("Submits"); },
loadingTemplate: 'loading'
});
Router.route('/submit/:_id', {
name: 'formDisplay',
data: function() {
return Submits.findOne({this.params._id});
}
});
And then I just have the average publish and find calls. My issues are I'm not sure how to perform the redirect on submit, and I am not sure how to display the form results on the newly generated route.
Any help would be appreciated.
I was able to do it by adding an autoform.hook and changing my routing a bit.
Autoform hook:
AutoForm.addHooks('insertSubmit', {
onSuccess: function(doc) {
Router.go('formDisplay',{_id: this.docId});
}
})
Routing:
Router.route('/submit/:_id', {
name: 'submitLayout',
data: function() { return Products.findOne(this.params._id);}
});
I got this information from this post:
Route to the new data submitted by Meteor autoform using iron router?

Vue JS Custom directive data binding

I'm creating a custom directive to make a form submit via ajax - however I can't seem to get validation errors to bind to the Vue instance.
I am adding my directive here:
<form action="{{ route('user.settings.update.security', [$user->uuid]) }}" method="POST"
enctype="multipart/form-data" v-ajax errors="formErrors.security" data="formData.security">
My directive looks like:
Vue.directive('ajax', {
twoWay: true,
params: ['errors', 'data'],
bind: function () {
this.el.addEventListener('submit', this.onSubmit.bind(this));
},
update: function (value) {
},
onSubmit: function (e) {
e.preventDefault();
this.vm
.$http[this.getRequestType()](this.el.action, vm[this.params.data])
.then(this.onComplete.bind(this))
.catch(this.onError.bind(this));
},
onComplete: function () {
swal({
title: 'Success!',
text: this.params.success,
type: 'success',
confirmButtonText: 'Back'
});
},
onError: function (response) {
swal({
title: 'Error!',
text: response.data.message,
type: 'error',
confirmButtonText: 'Back'
});
this.set(this.vm, this.params.errors, response.data);
},
getRequestType: function () {
var method = this.el.querySelector('input[name="_method"]');
return (method ? method.value : this.el.method).toLowerCase();
},
});
And my VUE instance looks like:
var vm = new Vue({
el: '#settings',
data: function () {
return {
active: 'profile',
updatedSettings: getSharedData('updated'),
formData: {
security: {
current_password: ''
}
},
formErrors: {
security: []
},
}
},
methods: {
setActive: function (name) {
this.active = name;
},
isActive: function (name) {
if (this.active == name) {
return true;
} else {
return false;
}
},
hasError: function (item, array, sub) {
if (this[array][sub][item]) {
return true;
} else {
return false;
}
},
isInArray: function (value, array) {
return array.indexOf(value) > -1;
},
showNotification: function () {
if (this.updatedSettings) {
$.iGrowl({
title: 'Updated',
message: 'Your settings have been updated successfully.',
type: 'success',
});
}
},
}
});
However, when I output the data, the value for formErrors.security is empty
Any idea why?
The issue is with the this.set(/* ... */) line. this.set doesn't work the same as Vue.set or vm.$set.
this.set attempts to set the path that you passed to the directive: v-my-directive="a.b.c". So running this.set('foo') will attempt to set $vm.a.b.c to 'foo'.
What you want to do is this:
(ES6)
this.params.errors.splice(0, this.params.errors.length, ...response.data)
(Vanilla JS)
this.params.errors.splice.apply(this.params.errors, [0,this.params.errors.length].concat(response.data))
That will update whatever Object is tied to the errors param on the DOM Node. Make sure that you do v-bind:errors="formErrors.security" or :errors="formErrors.security".

Subscribing the collection (Meteor)

I have some specific problem.
I use MeteorJS and installed yogiben:admin. I tried to build some schema, but I have an error after updating something.
I want to add that I have subpages in page, maybe that's the problem?
That's what I get after adding items to my invoice:
http://s7.postimg.org/l0q52l27v/error.png
As I can see in the picture, the problem is with some modifier and with "After.Update.sum". I use function that use "sum".
In my "server/collections/invoices_item.js"
I have:
InvoicesItem.after.update(function(userId, doc, fieldNames, modifier, options) {
var sum = 0; InvoicesItem.find({ invoiceId: doc.invoiceId }).map(function(item) { sum += item.amount; }); Invoices.update({ _id: doc.invoiceId }, { $set: { totalAmount: sum }});
});
Than I saw that problem could be with "totalAmount:sum". I use Chrome, so I tried "console.log()" to see if the page takes my collection.
And it doesn't.
I use Chrome, so I tried to see what the console will give me. I have something like this: http://s4.postimg.org/rusm4wx9p/fakturka.png
I did sth like that in my code on server side:
Meteor.publish("fakturka", function(invoiceId) {
return Invoices.find({_id:invoiceId,ownerId:this.userId}, {});
});
And did that on client side:
this.InvoicesNewInsertController = RouteController.extend({
template: "InvoicesNew",
yieldTemplates: {
'InvoicesNewInsert': { to: 'InvoicesNewSubcontent'}
},
onBeforeAction: function() {
/*BEFORE_FUNCTION*/
this.next();
},
action: function() {
if(this.isReady()) { this.render(); } else { this.render("InvoicesNew"); this.render("loading", { to: "InvoicesNewSubcontent" });}
/*ACTION_FUNCTION*/
},
isReady: function() {
var subs = [
Meteor.subscribe("invoices_item"),
Meteor.subscribe("invoiceeeee"),
Meteor.subscribe("customers"),
Meteor.subscribe("fakturka", this.params.invoiceId),
Meteor.subscribe("invoices_item_empty_faktura"),
Meteor.subscribe("invoices_itemss_faktura", this.params.invoiceId)
];
var ready = true;
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
return {
params: this.params || {},
invoices_item: InvoicesItem.find({}, {}),
invoiceeeee: Invoices.find({}, {}),
customers: Customers.find({}, {}),
fakturka: Invoices.findOne({_id:this.params.invoiceId}, {}),
invoices_item_empty_faktura: InvoicesItem.findOne({_id:null}, {}),
invoices_itemss_faktura: InvoicesItem.find({invoiceId:this.params.invoiceId}, {})
};
/*DATA_FUNCTION*/
},
onAfterAction: function() {
}
});
I'm sorry for so much code, but I really want to solve that problem and I want to give so much info as I could. Please, help me to solve my problem.
After removing that code from: both/collections/invoices.js
Schemas={};
Schemas.Invoicess = new SimpleSchema({
invoiceNumber:{
type:Number
},
date_issued:{
type:Date
},
date_due:{
type:Date
},
customerId:{
type:String
},
totalAmount:{
type:String
}
});
Invoices.attachSchema(Schemas.Invoicess);
"fakturka" is visible. After adding that code - "fakturka" in undefined.

Meteor Router.go not passing params

Snippet of code client-side:
Template.projectEditButton.events({
"click .edit": function() {
Router.go('projectForm', {prjId: this._id});
}
});
At this point, this._id is correct. In router file:
Router.route('/projects/form', {
name: 'projectForm',
data: function() {
return Projects.findOne(this.params.prjId);
}
});
this.params is empty. What am I missing?
You need to add the parameter to your route definition in order for the mapping to work:
Router.route('/projects/form/:prjId', {
name: 'projectForm',
data: function() {
return Projects.findOne(this.params.prjId);
}
});

Set value in Backbone.Form after fetch from the server

Hi I am newbie in Backbone and JS.
I need to fetch data from the server and put this value as the default to planProviderMode choice radio button. So i fetch the data in defaultMode variable. But the call is a asynchronous and I receive a value after the planProviderMode: defaultMode.value code has been executed.
var PlanProviderMode = Backbone.Model.extend({
url: '/rest/enrollment/step/plan-provider-mode'
});
var defaultMode = new PlanProviderMode;
defaultMode.fetch({
success: function() {
// recieve correct data
}
});
var formItems = new Backbone.Form({
template: tpl,
className: 'wizard-content',
schema: {
planProviderMode: {
template: formTpl,
type: 'Radio',
options: [
{
label: 'By Plan',
val: 'BY_PLAN',
custom: {
img: '../resources/img/by-plan.jpg'
}
},
{
label: 'By Provider',
val: 'BY_PROVIDER',
custom: {
img: '../resources/img/by-provider.jpg'
}
}
]
}
},
//here i put the default value
data: {
planProviderMode: defaultMode.value
}
});
How could I set the fetched value to the form.
Please let me know if the question is not described well. Thanks.
you should write such code in success callback function which is executed only after the fetch request is completed succesfully.
var PlanProviderMode = Backbone.Model.extend({
url: '/rest/enrollment/step/plan-provider-mode'
});
var defaultMode = new PlanProviderMode;
defaultMode.fetch({
success: function() {
// recieve correct data
//here you put the default value
data: {
planProviderMode: defaultMode.value
}
}
});
var formItems = new Backbone.Form({
template: tpl,
className: 'wizard-content',
schema: {
planProviderMode: {
template: formTpl,
type: 'Radio',
options: [
{
label: 'By Plan',
val: 'BY_PLAN',
custom: {
img: '../resources/img/by-plan.jpg'
}
},
{
label: 'By Provider',
val: 'BY_PROVIDER',
custom: {
img: '../resources/img/by-provider.jpg'
}
}
]
}
}
});
Backnone has a function called "parse" that helps you in this cases.
This function will always be called from backbone before the data from server populate the model.
Take a read in parse method.
There's a answer here.
how to override Backbone's parse function?
Hope it helps

Categories

Resources