Meteor user adding form doesn't do anything? - javascript

So I made my own user adding form so that only logged in users can add new ones. Here's my Jade:
template(name="userAdd")
.sixteen.wide.column
h1 Add new user
form#userAddForm.ui.form
.field.required
label(for="username") Username:
input(type="text" name="username")#username
.field.required
label(for="email") Email:
input(type="email" name="email")#email
.field.required
label(for="password") Password:
input(type="password" name="password")#password
.field.required
label(for="realname") Real Name:
input(type="text" name="realname")#realname
.field.required
label(for="bio") Bio:
textarea(rows="3" name="bio")#bio
button(type="submit")#usersubmit.ui.button.primary Submit
And the Javascript:
Template.userAdd.events({
'click #usersubmit': function (evt) {
Accounts.createUser({
username: $('input #username').val(),
email: $('input #email').val(),
password: $('input #password').val(),
profile: {
realname: $('input #realname').val(),
bio: $('input #bio').val()
}
})
Router.go('/')
}
})
For some reason, this only redirects me back to the same page and doesn't do anything, not even something shows in the dev console. What am I doing wrong?

Because it is actually submitting the form. You need to stop the form from submitting. Use the following code.
Template.userAdd.events({
'submit form': function(event){
event.preventDefault();
Accounts.createUser({
username: event.target.username.value,
email: event.target.email.value,
password: event.target.password.value,
profile: {
realname: event.target.realname.value,
bio: event.target.bio.value
}
});
Router.go('/');
}
});
Notice that I use event.target.inputName.value which is the best practice way of dealing with form data in Meteor.

Related

Formik handleSubmit is not getting called

I'm trying to validate a form before submitting using formik and yup validation. The form consist of two parts, the first form is validated then loads next one. And am setting a state handleShow(true) to trigger the second form. Below is my code
const UserOnboardSchema = Yup.object().shape({
gender: Yup.string().required('please select the gender'),
firstName: Yup.string().required('Please enter your first name'),
lastName: Yup.string().required('Please enter your last name'),
mobile: Yup.string()
.required('Please enter your mobile number')
.matches(phoneRegExp, 'Please enter valid phone number'),
workExperience: Yup.string().required('Please enter your work experience'),
});
const formik = useFormik({
initialValues: {
gender: '',
firstName: '',
lastName: '',
mobile: '',
workExperience: '',
currentRole: '',
},
validationSchema: UserOnboardSchema,
onSubmit: (values) => {
console.log(values);
formik.resetForm();
},
});
const handleSubmit = (e) => {
e.preventDefault();
formik.handleSubmit();
if (Object.entries(formik.errors).length === 0) {
handleShow(true);
} else {
handleShow(false);
}
};
Here is the problem in the handleSubmit the formik.handleSubmit is not working. It's directly accessing the if/else condition thus loading second form without validating the first one.
if (Object.entries(formik.errors).length === 0) {
handleShow(true);
} else {
handleShow(false);
}
but if I givehandleShow(true) direclty to formik, like this
const formik = useFormik({
initialValues: {
gender: '',
firstName: '',
lastName: '',
mobile: '',
workExperience: '',
currentRole: '',
},
validationSchema: UserOnboardSchema,
onSubmit: (values) => {
console.log(values);
handleShow(true); #----> Giving here.
formik.resetForm();
},
});
then the formik and Yup validation works. Im unable to figure out whats causing this issue?
It's difficult to see what's wrong without the form itself. Here are some helpful troubleshooting tips though...
Formik won't trigger the onSubmit method, if there are errors in the form. So, my go-to would be to:
Check for any errors in the form,
Look at the initialValues object for any unused fields

Posting data via JSON when checkbox id/name contains hyphen

I'm trying to use postUserData so that if a person fills in and submits a form on one page of my website, it submits the data to a form on a different page on my website.
It all worked until I introduced a checkbox named writerep to my form, as my CMS autogenerates the checkbox name on the final form (in this case, the catchy "custom-1798_0", and because that ID/name contains a hyphen, it breaks the JSON. Other checkbox without hyphen works fine. Code below:
$('#user_info_form').validate({
submitHandler: function submitHandler(form, e) {
e.preventDefault();
var firstname = e.target.firstname.value;
var lastname = e.target.lastname.value;
var email = e.target.email.value;
var country = e.target.country.value;
var writerep = e.target.writerep.checked;
var emailopt = e.target.emailopt.checked;
userInfo = {
firstname: firstname,
lastname: lastname,
email: email,
country: country,
custom-1798_0: writerep? 1 : 0,
email_opt_in: emailopt ? 1 : 0
};
postUserData(userInfo, 'https://*********');
nextSlide('.slide1');
},
rules: {
firstname: "required",
lastname: "required",
country: "required",
email: {
required: true,
email: true
}
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
country: "Please select your country",
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
}
}
});
Without renaming the checkbox on the final form, which isn't possible due to CMS limitations, is there a way of making this work?
You have to quote property names that have special characters or spaces in them. Some are allowed like $ and _ but - is not since it is also an operator
userInfo = {
firstname: firstname,
lastname: lastname,
email: email,
country: country,
'custom-1798_0': writerep? 1 : 0,
email_opt_in: emailopt ? 1 : 0
};

Validation Taking 5-10 sec on Form Submit

I have a very simple registration form only requiring a username, email, and password. I am trying to see why it takes 5-10sec to complete the registration after the user submits. I tried profiling on the server-end (see here), and have eliminated that as the problem.
It looks like my issue is the client-side validation. I am using the https://jqueryvalidation.org/ JS file plus another custom file that tells the user if they are trying to use a name or password that already exists:
$('.register-form').validate({
submitHandler: function(form){
$('.register-form').submit();
},
rules: {
password: {
required: true
},
tos: {
required: true
},
username: {
required: true,
remote: '/api/v1/users/username/'
},
email: {
required: true,
email: true,
remote: '/api/v1/users/email/'
},
},
messages: {
first_name: {
required: 'Please include your first name.'
},
last_name: {
required: 'Please include your last name.'
},
password: {
required: 'Please create a password'
},
tos: {
required: 'Please check that you agree to our TOS and Privacy Policy'
},
email: {
required: 'Please include your email.',
email: 'Please insert a valid email address.',
remote: 'This email is already in use.'
},
username: {
required: 'Please create a username.',
remote: 'This username is already in use.'
}
}
});
When I use Chrome's profiling (picture link), it looks like the problem is about 10sec of thousands of tiny tasks where register.js and the jquery.validator.js are calling each other. Specifically, its always submitHandler: function(form) line that is triggered on register.js. So I think I see the problem, but I am not clear on how to interpret it or fix it.
Any ideas? I am pretty new to using these validation plug-ins.
this line
$('.register-form').submit();
should read
form.submit();
so the function should look like this
$('.register-form').validate({
submitHandler: function(form) {
form.submit();
},
rules:...
});
other wise you keep recursively calling submit
from the documentation
Example: Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the validation isn't triggered again.
https://jqueryvalidation.org/validate/

Is it possible to insert(not update) a field name as variable in Mongodb?

Im trying to insert a embedded document in mongodb for a meteor project.
'submit form' : function(event){
event.preventDefault();
var query=document.getElementsByClassName("twilioProcessorsms")[0].value;
ChoiceList.insert({
sms: esms,
query: {
accountSID: accsid,
authToken: token,
phoneNumber: phno}
});
I am trying to have the "query" as a variable. But it considers query as a string.I dont want to achieve this with an update. Pls help !
Something like this should work:
'submit form' : function(event){
event.preventDefault();
var query=document.getElementsByClassName("twilioProcessorsms")[0].value;
var valueToInsert = {
sms: esms
};
valueToInsert[query] = {
accountSID: accsid,
authToken: token,
phoneNumber: phno}
};
ChoiceList.insert(valueToInsert);

Insert data in collection at Meteor's startup

I would like to insert data at Meteor's startup. (And after from a JSON file)
At startup, I create a new account and I would like to insert data and link it to this account once this one created.
This is the code that creates the new account at startup:
if(!Meteor.users.findOne({emails: { $elemMatch: { address: "test#test.com"}}})){
var id = Accounts.createUser({ email: "test#test.com", password: "1234", profile: { name: 'Test' } });
Meteor.users.update({_id: id }, { $set: { admin: false }});
}
And after that, I need to insert data and link it to this account with its ID. (In different collections).
So I tried to do something like that, but obviously It didn't work:
UserData = new Mongo.Collection('user_data');
if(!Meteor.users.findOne({emails: { $elemMatch: { address: "test#test.com"}}})){
var id = Accounts.createUser({ email: "test#test.com", password: "1234", profile: { name: 'Test' } });
Meteor.users.update({_id: id }, { $set: { admin: false }});
UserData.insert({
createdBy: id,
firstname: "test",
/* ... */
});
}
EDIT
Sorry for not have been clear.
The real issue is the :
UserData = new Mongo.Collection('user_data');
declaration is in another file, so I can't do like above.
As it's not in the same file, I tried to get the userId that got "test#test.com" as the email (the account's email created at startup). And once I got it, I want to use it in "createdBy: ID_HERE".
Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later.
Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js.
So if you put your insert code into server/fixtures.js it'll work.

Categories