Right now, my Posts model has a title and a content field:
client/client.js:
Meteor.subscribe('all-posts');
Template.posts.posts = function () {
return Posts.find({});
};
Template.posts.events({
'click input[type="button"]' : function () {
var title = document.getElementById('title');
var content = document.getElementById('content');
if (title.value === '') {
alert("Title can't be blank");
} else if (title.value.length < 5 ) {
alert("Title is too short!");
} else {
Posts.insert({
title: title.value,
content: content.value,
author: userId #this show displays the id of the current user
});
title.value = '';
content.value = '';
}
}
});
app.html:
<!--headder and body-->
<div class="span4">
{{#if currentUser}}
<h1>Posts</h1>
<label for="title">Title</label>
<input id="title" type="text" />
<label for="content">Content</label>
<textarea id="content" name="" rows="10" cols="30"></textarea>
<div class="form-actions">
<input type="button" value="Click" class="btn" />
</div>
{{/if}}
</div>
<div class="span6">
{{#each posts}}
<h3>{{title}}</h3>
<p>{{content}}</p>
<p>{{author}}</p>
{{/each}}
</div>
</div>
</div>
</template>
I tried adding an author field (already did meteor add accounts-password and accounts-login):
author: userId
But it just shows the id of the current user who is logged in.
I would like it to show the email of the author of the post instead.
How to accomplish that?
I think you can get the email with
Meteor.users.findOne(userId).emails[0];
#danielsvane is correct, but since your Post document's author field stores the _id of the author and not the email address, you'll need a template helper in order for the template to know how to get the email address. Try the following:
// html
...
<div class='span6'>
{{#each posts}}
{{> postDetail}}
{{/each}}
</div>
...
<template name="postDetail">
<h3>{{title}}</h3>
<p>{{content}}</p>
<p>{{authorEmail}}</p>
</template>
// javascript
Template.postDetail.helpers({
// assuming the `author` field is the one storing the userId of the author
authorEmail: function() { return Meteor.users.findOne(this.author).emails[0]; }
});
If it's always showing the current user and not the user who is the author of the post, then the problem lies in how you're setting the value of the userId variable in your event handler, which isn't code that you showed in your question.
Related
I am trying to pass git variable to settings which is wrapping with with as shown below
If we can see right now it is setting.gitlab but i want to make it dynamically like setting.git where git is a variable mentioned in each loop .
{{#each git in gitlabFields}}
{{#with settings.gitlab}}
<div data-value={{#index}}>{{git}}</div>
<div>hihi</div>
<div class="rc-user-info__row">
<div class="rc-input">
<label class="rc-input__label">
<div >
<div class="rc-input__title" style="display: inline-block;" >{{_ label}}{{equal default value '*'}}</div>
</div>
<!-- {{#each gitlabFields}} -->
<div id="dynamicFields">
<div class="rc-input__wrapper" >
<input type="text" name="{{git}}" value="{{value}}" class="rc-input__element js-input" disabled="{{./disabled}}"/>
</div>
</div>
<!-- {{/each}} -->
</label>
</div>
</div>
{{/with}}
{{/each}}
git variable is not accessible here settings.git
Its showing undefined .
Assuming settings is an accessible Object, you can write a helper, that resolves the value:
Template.myTemplate.helpers({
getGitSettings (settings, key) {
return settings[key]
}
})
If you want to decouple settings from the template or avoid passing it through the whole display list you can also define it within the Template module as private variable:
const gitSettings = { ... };
Template.myTemplate.helpers({
getGitSettings (settings, key) {
return gitSettings[key]
}
})
If this pattern is used among many Templates you can also define a global helper:
const gitSettings = { ... };
Template.registerHelper('gitSettings', function (key) {
return gitSettings[key]
})
and use it via
{{#each field in gitlabFields}}
{{#with gitSettings field}}...{{/with}}
{{/each}}
The code below is trying to grab the username and password from input elements on a template.login and createUser when a button which is in template.footer is clicked.
Being new to javascript and Meteor, my code below probably butchered both.
I thought to make a method call from the footer click event, this call gets the username and password and fires Meteor accounts create and store the returned userId in a local session to be used later. blah..blah..
But how can I get access to input values in one template from another?
so I need your help. Thanks
Template.footer.events({
'click .myClass': function (event, template) {
Meteor.call('loginUser', username,password);
}
});
Meteor.methods({
//store the useId returned from createUser in a local session userId
loginUser: function (username, password) {
Accounts.createUser(username, password, function () {
Session.set(userId, this.value);
});
}
});
<template name="footer">
<footer>
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="container">
<div class="row">
{{#each footerButtons}}
<h2>
<button class="col-xs-{{footerButtonsScaling}} myClass" type="button">{{text.toUpperCase}}</button>
</h2>
{{/each}}
</div>
</div>
</nav>
</footer>
</template>
<template name="login">
<form action="">
<input type="text" name="username" placeholder="type your ID" value="{{username}}">
<input type="password" name="password" placeholder="type your PIN" value="{{password}}">
</form>
</template>
You can just use jQuery to access field values anywhere in the DOM:
var username = $('[name="username"]').val();
var password = $('[name="password"]').val();
Im creating a an instant messenger app and im having a little trouble routing it. So, once you go into the app. There is a list of available users. You can click on a user and start chatting. The issue I have is once I click send, the console show an Uncaught TypeError: Cannot read property 'value' of undefined. Im not sure what im doing wrong here. Also I need help show the chat messages sent above. As if you can see the recent and previous messages. Here are my codes. Any examples and helps would be great.
HTML
minstant
<body>
</body>
<!-- this is the main template used by iron:router to build the page -->
<template name="ApplicationLayout">
{{> yield "header"}}
<div class="container">
{{> yield "main"}}
</div>
</template>
<!-- top level template for the nav bar -->
<template name="navbar">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">
Minstant!
</a>
</div>
<div class="nav navbar-nav">
{{> loginButtons}}
</div>
</div>
</nav>
</template>
<!-- Top level template for the lobby page -->
<template name="lobby_page">
{{> available_user_list}}
</template>
<!-- display a list of users -->
<template name="available_user_list">
<h2>Choose someone to chat with:</h2>
<div class="row">
{{#each users}}
{{> available_user}}
{{/each}}
</div>
</template>
<!-- display an individual user -->
<template name="available_user">
<div class="col-md-2">
<div class="user_avatar">
{{#if isMyUser _id}}
<div class="user_avatar">{{getUsername _id}} (YOU)
<br/>
<img src="/{{profile.avatar}}" class="avatar_img">
</div>
{{else}}
<a href="/chat/{{_id}}">
{{getUsername _id}}
<br/>
<img src="/{{profile.avatar}}" class="avatar_img">
</a>
{{/if}}
</div>
</div>
</template>
<!-- Top level template for the chat page -->
<template name="chat_page">
<h2>Type in the box below to send a message!</h2>
<div class="row">
<div class="col-md-12">
<div class="well well-lg">
{{#each recentMessages}}
{{> message}}
{{/each}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form class="new-message">
<input class="input" type="text" name="chat" placeholder="type a message here...">
<button class="btn btn-default">Send</button>
</form>
</div>
</div>
</template>
<!-- simple template that displays a message -->
<template name="message">
<div class = "container">
<div class = "row">
<div class = "username">{{username}}
<img src="/{{profile.avatar}}" class="avatar_img">
</div>
<div class = "message-text"> said: {{messageText}}</div>
</div>
</div>
</template>
Here is my JS
Messages = new Mongo.Collection("messages");
if (Meteor.isClient) {
Meteor.subscribe("messages");
Meteor.subscribe("userStatus");
// set up the main template the the router will use to build pages
Router.configure({
layoutTemplate: 'ApplicationLayout'
});
// specify the top level route, the page users see when they arrive at the site
Router.route('/', function () {
console.log("rendering root /");
this.render("navbar", {to:"header"});
this.render("lobby_page", {to:"main"});
});
// specify a route that allows the current user to chat to another users
Router.route('/chat/:_id', function () {
this.render("navbar", {to:"header"});
this.render("chat_page", {to:"main"});
});
///
// helper functions
///
Template.available_user_list.helpers({
users:function(){
return Meteor.users.find();
}
})
Template.available_user.helpers({
getUsername:function(userId){
user = Meteor.users.findOne({_id:userId});
return user.profile.username;
},
isMyUser:function(userId){
if (userId == Meteor.userId()){
return true;
}
else {
return false;
}
}
})
Template.chat_page.helpers({
recentMessages: function () {
return Messages.find({}, {sort: {createdAt: 1}});
return Meteor.users.find();
},
});
Template.chat_page.events({
// this event fires when the user sends a message on the chat page
'submit .new-message':function(event){
event.preventDefault();
var text= event.target.text.value;
// stop the form from triggering a page reload
event.target.text.value = "";
// see if we can find a chat object in the database
// to which we'll add the message
Meteor.call("SendMessage", text);
},
});
};
Meteor.methods({
sendMessage: function (messageText) {
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Messages.insert({
messageText: messageText,
createdAt: new Date(),
username: Meteor.user().username
});
}
});
// start up script that creates some users for testing
// users have the username 'user1#test.com' .. 'user8#test.com'
// and the password test123
if (Meteor.isServer) {
Meteor.startup(function () {
if (!Meteor.users.findOne()){
for (var i=1;i<9;i++){
var email = "user"+i+"#test.com";
var username = "user"+i;
var avatar = "ava"+i+".png"
console.log("creating a user with password 'test123' and username/ email: "+email);
Meteor.users.insert({profile:{username:username, avatar:avatar}, emails: [{address:email}],services:{ password:{"bcrypt" : "$2a$10$I3erQ084OiyILTv8ybtQ4ON6wusgPbMZ6.P33zzSDei.BbDL.Q4EO"}}});
}
}
},
),
Meteor.publish("messages", function () {
return Messages.find();
});
Meteor.publish("userStatus", function() {
return Meteor.users.find({ "status.online": true });
});
};
The error is with your form submit code. In the console you can see the error is in Template.chat_page.events.submit .new-message on line 73. That will take you right to the error code:
'submit .new-message':function(event){
event.preventDefault();
var text = event.target.text.value;
// stop the form from triggering a page reload
event.target.text.value = "";
}
event.target.text.value doesn't exist. event.target does, but there is no field for text. There is textContent, and you can access the children of the target (which in this case is the form). Put in a console.log(event); and figure out what you are trying to access within the javascript console and then use that to determine what your code should look like. This might work for you:
'submit .new-message':function(event){
event.preventDefault();
var text = event.target.elements.chat.value;
// stop the form from triggering a page reload
event.target.text.value = "";
}
event.target.elements.chat.value comes from the name field of the <input>.
I'm stumped as to why part of my code isn't displaying when the session variable is set to true. When the user selects a certain option from the dropdown, based on the value, it changes the warmerselected to TRUE. I have tracked this in the console, and it works just fine.
Here is my code:
HTML:
<div class="item">
<div class="ui label">Product Type:</div>
<select id="ProductType" name="ProductType">
{{#each ProductTypes}}
<option value="{{ProductTypeAbbrev}}">{{ProductTypeName}}</option>
{{/each}}
</select>
</div>
{{#if warmerselected}}
<div class="item">
<div class="ui label">Name:</div>
<input type="text" name="ProductName" placeholder="Enter Product Name">
</div>
{{/if}}
JS:
Session.setDefault("warmerselected", false);
Template.addProduct.events({
'change #ProductType': function (e) {
var selitem = $("#ProductType").val();
if(selitem == "WA") {
Session.set("warmerselected",true)
}else {
Session.set("warmerselected",false);
}
}
});
Template.addProduct.helpers({
warmerselected: function(){
return Session.get("warmerselected");
}
});
Session isn't meant to be helper in HTML, you have to create one
I have two Collection : a collection A which include array of B ids.
Template A :
<template name="templateA">
Name : {{name}} - {{_id}}
{{#each allBsOfThisA}}
{{> Bdetail}}
{{/each}}
Add B for this A
</template>
Note : in this templateA, I list all A and their detail informations. At bottom of the A, I putted a link to add a B.
Template of Bsubmit :
<div class="form-group {{errorClass 'nameOfB'}}">
<label class="control-label" for="nameOfB">nameOfB</label>
<div class="controls">
<input name="nameOfB" id="nameOfB" type="text" value="" placeholder="nameOfB" class="form-control"/>
<span class="help-block">{{errorMessage 'nameOfB'}}</span>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
On the Bsubmit script : I want to get the ID of A. I tried with template.data._id but it's not working :
Template.Bsubmit.events({'submit form': function(e, template) {
e.preventDefault();
console.log("template.data._id: " + template.data._id);
var B = {
name: $(e.target).find('[name=name]').val(),
AId : template.data._id
};
}
});
EDIT :
BSubmit's iron-router part :
Router.route('Bsubmit ', {name: 'Bsubmit '});
Neither the template nor the route does know about the A-instance of the other template/route.
So one solution would be to pass the id to the route, which allows you to fetch the instance or use the id directly:
Template:
<template name="templateA">
Name : {{name}} - {{_id}}
{{#each allBsOfThisA}}
{{> Bdetail}}
{{/each}}
Add B for this A
</template>
Route:
More information about passing arguments to a route
Router.route('/Bsubmit/:_id', function () {
var a = A.findOne({_id: this.params._id});
this.render('Bsubmit', {data: a});
});
Then you could use template.data._id in the event.
Another solution would be to embed the form into the other view, so you can access the data of the parent template in there (documentation of parentData).