Meteor, how to submit an array of forms - meteor

I have a Meteor application where I want to describe a "site" and a number of "ios" (input/outputs) for each site. The site is described by the first 3 fields and stored in a collection named sites. The ios are entered below that, and are stored in a collection named ios. The idea is each site may have an arbitrary number of ios. I would like to be able to edit any field for the site or any of the ios, click save, and have everything saved at once. Because the number of ios will be limited to say 5 or so by physical circumstances, I think this will be a better user experience than having a separate edit page for ios. However, I can't figure out how to save the ios when the site form is saved. How could this be implemented?
Here is an image of what the form looks like:
https://app.box.com/s/rqjj9lb49twcitwo7rmdy6k9ta0vuztv

Assuming a structure like this:
<template name="form">
<form name="form">
<input type="text" name="foo" />
<input type="text" name="bar" />
<button type="submit">Submit Form</button>
</form>
</template>
Some code like this will add your different elements to different collections:
Template.form.events({
'submit form[name="form"]': function(e) {
var foo, bar, fooInsert, barInsert;
e.preventDefault();
foo = $(e.target).find('[name="foo"]').val();
bar = $(e.target).find('[name="bar"]').val();
fooInsert = {
thing: foo
}
barInsert = {
thing: bar
}
fooInsert._id = Collection1.insert(fooInsert); // Insert foo into Collection1
barInsert._id = Collection2.insert(barInsert); // Insert bar into a different collection, Collection2
}
});
It would help if you did show some code you're working with so we can make our answers better :)

Related

Cascading dropdowns on Mediawiki site

This is my first post here. I am not a developer but have learned a bit about CSS the last few months. I have a basic Mediawiki site which has raw HTML enabled on the site which is a secure site and only a very limited number of users with edit privilege's.
I am trying to make it so that when a user clicks the "Submit" button on the HTML form for the cascading dropdown, it will take them to a specific section on a page, based on what they have chosen in all the drop down boxes. I have used the w3schools site to borrow some code snippets.
Here is my form:
<html>
<form name="form1" id="form1" action="Front-end#CSS#Backgrounds">
Subjects: <select name="subject" id="subject">
<option value="" selected="selected">Select subject</option>
</select>
<br><br>
Topics: <select name="topic" id="topic">
<option value="" selected="selected">Please select subject first</option>
</select>
<br><br>
Chapters: <select name="chapter" id="chapter">
<option value="" selected="selected">Please select topic first</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</html>
And here is the java script I am using.
var subjectObject = {
"Front-end": {
"HTML": ["Links", "Images", "Tables", "Lists"],
"CSS": ["Borders", "Margins", "Backgrounds", "Float"],
"JavaScript": ["Variables", "Operators", "Functions", "Conditions"]
},
"Back-end": {
"PHP": ["Variables", "Strings", "Arrays"],
"SQL": ["SELECT", "UPDATE", "DELETE"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("subject");
var topicSel = document.getElementById("topic");
var chapterSel = document.getElementById("chapter");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
//display correct values
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() {
//display correct values
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}
In my form example above I hard coded the action= portion to say Front-end#CSS#Backgrounds
When I click the submit button it launches or takes me to this URL:
https://mysitename.com/myenvironment/index.php/Front-end?subject=Front-end&topic=CSS&chapter=Backgrounds#CSS#Backgrounds
In the example subject = my page name, in this case Front-end, topic = my Heading 1 section, in my case CSS, and chapter = my Heading 2 section, in my case Backgrounds.
But it's not working fully. When I click submit it takes me to the "Front-end" page on my Mediawiki site but it doesn't recognize or do anything with the Heading 1 and Heading 2 parts.
The way this will be used is to allow the user to select the page and section of a page they will be going to. So that in a form using three cascading dropdowns, the user will first pick the subject, which is actually the name of the page on my Mediawiki site, the second drop down will be the Heading 1 section, and the third drop down will be the Heading 2 section which is where I want the user to end up on the page.
The Mediawiki page sort of looks like this:
Page name is "Front-end"
Table of contents is for example:
## CSS ##
### Borders ###
### Margins ###
### Backgrounds ###
### Float ###
I will have the HTML cascading dropdown forms setup with three boxes. In my example, the user picks Front-end -- CSS -- Backgrounds and when they hit submit they go directly to the Heading 2 section on my page for "Backgrounds" Obviously, I need to code it so that whatever combination the user picks I take them to the right page section.
Any ideas on how I can do this? I would like to stick with the simple HTML form and Java Script example above as it is easy for me. Any advice is appreciated! Thanks in advance and sorry for the long post.
GJ231
Well many things to check.. First of all.. https://mysitename.com/myenvironment/index.php/Front-end?subject=Front-end&topic=CSS&chapter=Backgrounds#CSS#Backgrounds
An url can jump to one Anchor. not two. So am I guessing you will need some more JavaScript on checking the Post url and figure out where to go to on the page depending on the Post url.
The content of the page would need to have Anchor links inside them, something like #-- e.g. #Front-End-CSS-Backgrounds
Then before you post, you should change the url to something like : https://mysitename.com/myenvironment/index.php/Front-end#Front-End-CSS-Backgrounds
That will bring the person to the right spot.
If you cannot create anchor links on the page, perhaps you can create divs with the same format Id's ? or Something similar. Then have JavaScript jump to the relevant ID based on the url.

use the same form for create and read operation

I have a master and a child component. The child component persists the data for the create mode as well as the edit mode. The child has a data section as follows which is being used when the component is in create mode
data() {
return {
title: '',
description: '',
organizer: '',
startdate: '',
enddate: '',
email: '',
phone: ''
}
},
and my inputs in create mode are as follows
<input type="text" placeholder="enter event title here" class="form-control" v-model="title">
In the edit mode, I am updating a prop value on the client as follows, which is
props:['currentevent']
The value of the currentevent is being passed from the master component to the child component and is also the value that is currently being edited.
so, the complete code for handling an input value looks like as follows
<input type="text" placeholder="enter event title here" class="form-control" v-if="currentevent" :value="currentevent.title">
<input type="text" placeholder="enter event title here" class="form-control" v-else v-model="title">
and in my save method (in the child component), I am checking if currentevent is empty or not. If it is empty then I trigger the add code otherwise, I trigger the update code.
Question : This works , but I have a large form and having to do this for each and every component is not a clean design . Can you please let me know what should I be doing ?
I totally appreciate your predicament. The best way to handle form data is to make it create/update agnostic. Here's what I'd recommend you try:
Instead of maintaining all the data fields as disparate properties, contain them in a single object, in this case I'm calling it eventObj for clarity:
data () {
return {
eventObj: {}
}
}
Then in your markup you'd reference them via the object:
<input type="text" placeholder="..." class="form-control" v-model="eventObj.title">
You'd then need to define a prop for passing in the data (as an object) from the parent component if you are editing:
props: {
currentevent: Object
}
And then you'd just need to map the incoming prop to the child component's data:
created() {
Object.assign(this.eventObj, this.currentevent || {})
}
Now when your inputs like <input v-model="eventObj.title"> are processed, if there is a saved title (that was passed in with currentevent) the field will be prepopulated with it, otherwise it will be blank.
I think this should help you in the right direction toward solving the complexity you're trying to figure out. There are other logistical issues involved with this kind of stuff in general, but I won't drone on. :)
The issue I see is you want to remove the v-if/else in the form. I will recommend here is keep your local data of child to be in sync with the props passed and only use local variable in the form.
One way to do this can be put a watcher on props and whenever props changes, update local variables and only use those variables in form.
watch: {
currentevent: function(newVal){
title = newVal.title,\
description = newVal.description
...
}
}

Meteor: resetPassword email link behavior

I'm trying to implement the "reset password" functionality in my Meteor app. I have a very simple implementation of it based on this tutorial: Julien's tutorial on gentlenode
There are several examples floating around that use this same basic approach. I did mine almost exactly like Julien's but I used only one template; I use an {{#if}} in my template that displays the 'reset password' form, if my session variable sResetPassword is not falsey. (I don't know how the correct template is supposed to get displayed in Julien's example and it doesn't work for me as it is written -- the template doesn't change.)
Here's the critical piece of code. Two different methods that both work on my local app, but neither one works on my hosted (modulus) app.
/* method one
if (Accounts._resetPasswordToken) {
Session.set('sResetPassword', Accounts._resetPasswordToken);
}
/* method two
Accounts.onResetPasswordLink( function(token) {
Session.set('sResetPassword', token);
});
On my deployed version (Modulus), the link opens up my app and just goes straight to the start screen. When I check the value of my sResetPassword session var, it's undefined, so somehow the value of the token never gets put into the var.
While we're on the subject, does anyone know how you are supposed to get the correct template to load when you use a separate template for the reset password form?
Here is how it works for us. Code:
var token, done;
Accounts.onResetPasswordLink(function (t, d)
{
token = t;
done = d;
setTimeout(()=>Router.go("reset_password"), 0);
});
Template["reset_password"].events({
"click #resetBtn": function (event:Event, instance:Blaze.TemplateInstance)
{
var password1: string = instance.$("#input_password1").val();
var password2: string = instance.$("#input_password2").val();
console.log(password1, password2);
if (password1 != password2)
{
return;
}
Accounts.resetPassword(token, password1, ()=>
{
done();
Router.go("somewhere");
});
}
});
Template:
<template name="reset_password">
<form data-parsley-validate>
<div class="input-field">
<input id="input_password1" type="password" class="validate" data-parsley-trigger="keyup" data-parsley-minlength="6" data-parsley-minlength-message = "Please provide a password that is at least a 6 characters long." required>
<label for="input_password1">New Password</label>
</div>
<div class="input-field">
<input id="input_password2" type="password" class="validate" data-parsley-trigger="keyup" data-parsley-minlength="6" data-parsley-minlength-message = "Please provide a password that is at least a 6 characters long." required>
<label for="input_password2">Again</label>
</div>
<button id="resetBtn" class="waves-effect btn">Reset Password</button>
</form>
OK, for whatever reason, replacing iron-router with flow-router fixed this issue for me. I created a new app with only the login and reset password functionality and it worked fine. I added iron-router and again it worked, but only dev mode. When I ran it in production mode, the problem returned. Replaced iron-router with flow-router (in both the test app and my full app) and now the problem is gone. The email link works as expected in both modes.

Template is re-rendered even though there is no data change

I'm struggling with an issue that I will explain giving a simple demo.
There's following very simple document in People Collection.
{
"_id" : "vxmLRndHgNocZouJg",
"fname" : "John" ,
"nicks" : [ "Johnny" , "Jo"]
}
Now let's consider following templates. Basically I display username and a list of nicknames with input field for adding more nicknames.
<head>
<title>test</title>
</head>
<body>
{{> name}}<br/>
{{> nicks}}
</body>
<template name="name">
<input type="text" value="{{fname}}"/>
</template>
<template name="nicks">
{{#each nicks}}
<div>{{this}}</div>
{{else}}
no nicks yet
{{/each}}
<input type="text" name="nicks"/>
<input type="submit"/>
</template>
My client javascript code is as follows:
Template.name.fname = function() {
return People.findOne({"fname" : "John"},{
transform : function(doc) {
return doc.fname;
}
});
}
Template.name.rendered = function() {
console.log('Template "name" rendered!');
}
Template.nicks.nicks = function() {
var john = People.findOne({"fname" : "John"});
if(john) return john.nicks;
}
Template.nicks.events({
'click input[type="submit"]' : function () {
var johnId = People.findOne({"fname" : "John"})._id; // demo code
People.update(johnId,{
$addToSet : {
nicks : $('input[name="nicks"]').val()
}
})
}
});
My problem is that after adding nickname (update of nicks field in a document) template name is re-rendered (I know because I console.log it). When I query People collection to provide data for name template I use transform option so changes in nicks field shouldn't have impact on name template.
Meteor docs supports this:
Cursors are a reactive data source. The first time you retrieve a cursor's documents with fetch, map, or forEach inside a reactive computation (eg, a template or autorun), Meteor will register a dependency on the underlying data. Any change to the collection that changes the documents in a cursor will trigger a recomputation.
Why template name is re-rendered then?
The template is re-rendered because you change the People collection.
When you alter the People collection, Meteor automatically assumes that everything that it provides data to needs to be recalculated. (Which your name template does via Template.name.fname.
Even though you transform the output of the cursor, the People collection has changed in some way. The query is done before the transform is used, in other words, its not the transform that is looked at but the whole collection.
Meteor thinks that perhaps your document with {'fname':'John'} may have some other field that might have changed and it needs to requery it to check (which the nicks field has been altered). The transform is then applied after the requery.
Your HTML might not actually change at this point, only if the cursor returns something different will the html be changed.
If it becomes an issue in any scenario (i.e forms being cleared or DOM being changed when it shouldn't be) you can use the {{#isolate}} {{/isolate}} blocks to ensure that only everything inside them is re-rendered and nothing outside.

Reactive updates not received in other browsertabs

Meteor promises reactive updates, so that views are auto-updated when data changes. The included leaderboard example demonstrates this. It runs fine when I test it: data is updated across several browsertabs in different browsers, as expected.
All set and go, I started coding with meteor and progress was being made, but when I tested for reactive updates across browertabs, I noticed that only after a short while the updates across tabs stopped.
I boiled down the problem to the following code, based on a new empty meteor project:
updatebug.html
<head>
<title>updatebug</title>
</head>
<body>
{{> form}}
</body>
<template name="form">
<form onsubmit="return false;">
{{#each items}}
{{> form_item }}
{{/each}}
</form>
</template>
<template name="form_item">
<div>
<label>{{name}}
<input type="text" name="{{name}}" value="{{value}}">
</label>
</div>
</template>
updatebug.js:
Items = new Meteor.Collection("items");
if (Meteor.is_client) {
Template.form.items = function () {
return Items.find();
};
Template.form_item.events = {
'blur input': function(e) {
var newValue = $(e.target).val();
console.log('update', this.name, this.value, newValue);
Items.update({_id: this._id}, {$set: {value: newValue}});
},
};
}
if (Meteor.is_server) {
Meteor.startup(function () {
if (Items.find().count() === 0) {
Items.insert({name: 'item1', value: 'something'});
}
});
}
Run in multiple browsertabs, start changing the value of the input in one tab. The other tabs will reflect the change. Goto the next tab and change the value. Repeat a couple of times.
After a while, no more updates are received by any other tabs. It seems that once a tab has changed the value, it does not receive/show any more updates.
Differences compared to the leaderboard example (since it's very similar):
The leaderboard uses no form controls
The leaderboard example does an increment operation on update, not a set
I am about to file a bug report, but want to be sure I am not doing anything stupid here, or missing an essential part of the Meteor Collection mechanics (yes, autopublish package is installed).
The issue here is input element preservation. Meteor will preserve the input state of any form field with an id or name attribute across a template redraw. The redraw is preserving the old text in your form element, because you wouldn't want to interrupt another user typing in the same field. If you remove the name attribute from the text box, each tab will update on blur.
In fact, I'm not sure why the first update works in your example. That may actually be the bug!
You can see it's not a data problem by opening the console in each browser. On each blur event you will get an updated document in every open tab. (Type Items.find().fetch())

Resources