How to pass form parameters into spring controller.
I need to submit the below form into this url "submit.htm".
<form data-bind="submit: save" action="forms/submit.htm" method="post">
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span> errors</legend>
<label>First name: <input data-bind='value: firstName'/></label>
<label>Last name: <input data-bind='value: lastName'/></label>
</fieldset>
<button type="submit">Go</button>
</form>
JS:
var viewModel = {
firstName: ko.observable().extend({
required: true,
minLength: 2,
maxLength: 10
}),
lastName: ko.observable().extend({
required: true
}),
tasks: ko.observableArray([]),
save: function() {
if (viewModel.errors().length == 0) {
ko.utils.postJson($("form")[0], this);
} else {
alert('Please check your submission.');
viewModel.errors.showAllMessages();
}
}
};
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel);
this is going to my controller.
But I didnot get those parameters in my controller. Also I dont know the way to get these params in my controller.
Related
I want to insert a new document into db using autoform. Autoform hook calls a meteor method on server to insert the document.
I have this in template...
{{#autoForm collection="Reports" id="addReport" type="insert"}}
<div class="row">
<div class="col s6">
{{> afQuickField name='hours'}}
</div>
</div>
<button class="btn waves-effect waves-light modal-action modal-close"><i class="material-icons">save</i></button>
{{/autoForm}}
Then...
AutoForm.hooks({
addReport: {
onSubmit: function(insertDoc) {
Meteor.call('addReport', insertDoc, function(error, result) {
if (error) alert(error.reason);
});
return false;
}
}
});
then the method on server...
Meteor.methods({
addReport: function(insertDoc) {
var report = _.extend(insertDoc, {
userId: Meteor.userId(),
});
return Reports.insert(report);
}
});
I have a createdAt and updatedAt fields in collection, but they all have autoValue thus, I believe no need to do insertion from client or in the meteor method.
So collection with schema looks like this:
Reports = new Meteor.Collection('reports');
Reports.attachSchema(new SimpleSchema({
hours: {
type: Number,
label: "Number of hours",
decimal: true
},
createdAt: {
type: Date,
label: "Created Date",
autoValue: function() {
if (this.isInsert) {
return new Date;
} else {
this.unset();
}
},
denyUpdate: true
},
updatedAt: {
type: Date,
autoValue: function() {
if (this.isUpdate) {
return new Date()
}
},
denyInsert: true,
optional: true
},
"userId": {
type: String,
autoform: {
type: "hidden",
}
},
}));
When i run meteor, form displays, but submit does nothing. No visual cue as to if any error. No error message in both client and server console.
what am I doing wrong or missing?
Since #Cristo GQ got it right, I just want to make sure the answer is clear enough for future visitors of this thread
The onSubmit hook will be used only for autoForms with type='normal' or without any type= at all
On another note, the before.insert hook is just for type='insert' And there is no before.normal hook
This mean that when using the onSubmit hook, we have to do any "before work" (like adding currentUser to the doc) inside the onSubmit itself.
aldeed/meteor-autoform documentation:
// Called when form does not have a `type` attribute
onSubmit: function(insertDoc, updateDoc, currentDoc) {
Meteor.call()...
}
I'm following discovermeteor book, and I'm trying to use some methods of the book, but using the meteor-autoform package.
post_submit.html
<template name="postSubmit">
{{#autoForm collection="Posts" id="insertPost"}} <-- no type
<div class="form-group">
<div class="controls">
{{> afQuickField name='title' class='title form-control'}}
</div>
</div>
<div class="form-group">
<div class="controls">
{{> afQuickField name='description' class='description form-control'}}
</div>
</div>
<input id="send" type="submit" value="Send" class="btn btn-primary"/>
{{/autoForm}}
</template>
post_submit.js
var postSubmitHook = {
onSubmit: function(insertDoc){
Meteor.call('postInsert', insertDoc, function(error, result) {
if (error){
Bert.alert(error.reason, 'danger', 'growl-top-right');
$('#send').removeAttr('disabled');
return;
}
Router.go('postPage', {_id: result._id});
});
return false;
}
};
AutoForm.addHooks('insertPost', postSubmitHook);
I try create user profile page with autoform, but autorofm tell me "Error: AutoForm: You must specify a collection when form type is insert."
I have only one way through the methods?
Please help me to solve the problem.
Helper
Template.accountForm.helpers({
userSchema: function () {
return Schema.User;
}
});
Template
<template name="accountForm">
<div class="panel-body">
{{#autoForm schema=userSchema collection=Users id="accountForm" type="insert"}}
<fieldset>
{{> afObjectField name='profile'}}
</fieldset>
<button type="submit" class="btn btn-primary">Insert</button>
{{/autoForm}}
</div>
</template>
Schema
Schema = {};
Schema.UserProfile = new SimpleSchema({
lastname: {
type: String
}
});
Schema.User = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email
},
createdAt: {
type: Date
},
profile: {
type: Schema.UserProfile,
},
services: {
type: Object,
optional: true,
blackbox: false
}
});
Meteor.users.attachSchema(Schema.User);
You don't need the helper function, just use the Meteor.users object.
{{#autoForm collection='Meteor.users' doc=currentUser type='update' id='accountForm'}}
{{> afQuickField name='profile'}}
<button type='submit' class="btn btn-primary">Save profile</button>
{{/autoForm}}
I am working on my first Meteor app that uses OAuth for login. Prior to this, all of my projects have used only the accounts-password portions.
I have a simple login for with a button to login via Google:
<template name="login">
<form id="login" role="form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" />
</div>
<button id="signin" class="btn btn-primary">Sign in</button>
<hr />
Or:<br />
<button id="loginWithFacebook">Login with Facebook</button>
<button id="loginWithGoogle">Login with Google</button>
<button id="loginWithTwitter">Login with Twitter</button>
</form>
</template>
I then have a event handler to capture the button click and call the loginWithGoogle:
...
"click #loginWithGoogle": function(e, t){
Meteor.loginWithGoogle({
requestPermissions: [],
loginStyle: "popup"
}, function(err) {
if (err) {
// TODO Need to do something here with the error...
console.log('Error: ', err);
} else {
Router.go('home');
}
});
}
...
On the server I setup OAuth for Google like thus:
ServiceConfiguration.configurations.remove({
service: "google"
});
ServiceConfiguration.configurations.insert({
service: "google",
clientId: "000000000000000",
loginStyle: "popup",
secret: "000000000"
});
Accounts.onCreateUser(function (options, user) {
console.log('Creating user: ' + user.username);
return user;
});
And in my route I have this:
if (Meteor.isClient) {
// Initialize the loading template before hand
Router.onBeforeAction('loading');
// Map the routes
Router.map(function() {
// Homepage
this.route('home', {
path: '/',
onBeforeAction: function() {
if (!Meteor.user()) {
console.log('User is not logged in. Displaying login form.');
Router.go('login');
} else {
console.log('User is already logged in:', Meteor.user());
}
}
});
// Login page
this.route('login', {
path: '/login'
});
});
}
So, I get the console log in the browser saying User is not logged in. Displaying login form., and when I click the Login with Google button I get the popup asking which Google account I want to use, then the confirmation page. But when I click the Accept button I get nothing. The Accounts.onCreateUser() doesn't seem to run, nor does the callback code on the loginWithGoogle(). How do I get this configured correctly so that the callback runs, and ultimately I am re-directed back to my homepage?
Your onCreateUser doesn't work because you don't have username specified.
Try using
if(user.services.google)
user.username = user.services.google.name
And by the way, why won't you use {{>loginButtons}}?
I am having a little bit of trouble outputting a image after a filepicker selection with the file picker plus package from meteor. How to I grab the uploaded image url or file path, so I can pass it into a form input and put it in a collection. Putting in into the collection isnt the part I am worried about its getting the path that I am having trouble with cheers.
All contained in postSubmit template.
I have a form with
<input type="filepicker" name="myName" />
and a img output in the same template
<img src="{{filepickerIdToUrl myName}}">
and a router file containg
Router.onBeforeAction(function(){
loadFilePicker('magickey');
//can leave out key if its in settings
this.next();
},{only:['postSubmit']});
Here is the full postSubmit template
<template name="postSubmit">
<form>
<label for="title">Title</label>
<input name="title" id="title" type="text" value="" placeholder="Name your post"/>
<button id="uploadImage" class="btn btn-info btn-sm"><i class="fa fa-upload"></i> Upload</button>
<input type="submit" value="Submit"/>
</form>
<img id="imagePreview" class="img-responsive" src="{{filepickerIdToImageUrl imageId placehold_it='500x350' h=200 w=300}}"/>
<button id="removeImage" class="btn btn-warning btn-sm"><i class="fa fa-trash-o"></i> Remove</button>
This is also my postSubmit events
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
image: $(e.target).find('[name=image]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
Thanks to Nate and the google groups link above, I got it working.
Here is my solved code, Right now it only shows the preview on the form and you can remove it by clearing the session value, but it will be easy enough to grab that session value and put it into the form on submit.
Thanks again Nate.
Template.postSubmit.created = function(){
Session.setDefault("imageId", null);
Session.setDefault("imageKey", null);
};
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
image: $(e.target).find('[name=image]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
},
'click #uploadImage':function(event, template){
event.preventDefault();
filepicker.pickAndStore(
{
mimetypes: ['image/gif','image/jpeg','image/png'],
multiple: false
},{
access:"public"
},
function(InkBlobs){
// the upload is now complete to filepicker - but the form hasnt persisted the values to our collection yet
Session.set("imageId", _.last(_.first(InkBlobs).url.split("/")));
Session.set("imageKey", _.first(InkBlobs).key);
// once the session changes are made, the form will now have the new values, including a preview of the image uploaded
},
function(FPError){
log.error(FPError.toString());
}
);
},
'click #removeImage':function(event, template){
event.preventDefault();
Session.set("imageId", "remove");
Session.set("imageKey", "remove");
}
});
Template.postSubmit.helpers({
'hideRemove':function(){
return Session.equals("imageId", null) || Session.equals("imageId", "remove");
},
'imageId':function(){
if(Session.equals("imageId", "remove"))
return "";
else
return Session.get("imageId") || "";
},
'imageKey':function(){
if(Session.equals("imageKey", "remove"))
return "";
else
return Session.get("imageKey") || "";
}
});
i have a form with few fileds and a submit button... when i click on the submit button the form should validate and throw me an error of missing data but whats happening is that, it post the data and than validate the form
what should i do to validate the form and then post the form?
<body>
<form class="cmxform" id="commentForm" method="post" action="">
<div class="subColumns paragraph">
<div class="lefty">
<div class="fontWeight7">
<label for="first_name">
First Name:</label>
<input id="first_name" class="text required" maxlength="200"
name="first_name" />
</div>
</div>
<div class="cdc-left">
<div class="fontWeight7">
<label for="last_initial">
Last Initial:</label>
<input id="last_initial" class="required text" maxlength="200"
name="last_initial" />
</div>
</div>
</div>
<input id="btnRegister" name="btnRegister" class="submit" type="submit" value="Submit Your Answer" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#commentForm").validate();
// validate the comment form when it is submitted
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
$("#commentForm").validate({
submitHandler: PostData
});
});
function PostData() {
debugger
var _firstName = commentForm.first_name.value;// $('#first_name').value; //first_name.value;
var _lastName = $('#last_initial').value; //last_initial.value;
var _city = $('#city').value; //city.value;
var _state = $('#state').value; //state.value;
var _country = $('#country').value; //country.value;
}
</script>
You're hooking up the the click event on the button, which happens before the submit event on the form, instead use the submitHandler callback option for .validate(), like this:
$("#commentForm").validate({
submitHandler: PostData
});
...and remove this click handler completely:
$('#btnRegister').click(function () {
PostData();
});
The submitHandler only executes when the validation was successful, which would be what you want here.
Why not do server-side validation using ASP.NET's validation controls? It has the advantage of being harder to override, as client-side validation can be disabled if the user configures his browser to not run JavaScript.