Skip to content
Permalink
Browse files

Created a form to submit comments.

chapter10-3
  • Loading branch information
tmeasday committed Oct 19, 2015
1 parent 62f7eb0 commit 1f82c0af0e4d91504516985c90c140c41218d79c
@@ -0,0 +1,12 @@
<template name="commentSubmit">
<form name="comment" class="comment-form form">
<div class="form-group {{errorClass 'body'}}">
<div class="controls">
<label for="body">Comment on this post</label>
<textarea name="body" id="body" class="form-control" rows="3"></textarea>
<span class="help-block">{{errorMessage 'body'}}</span>
</div>
</div>
<button type="submit" class="btn btn-primary">Add Comment</button>
</form>
</template>
@@ -0,0 +1,38 @@
Template.commentSubmit.onCreated(function() {
Session.set('commentSubmitErrors', {});
});

Template.commentSubmit.helpers({
errorMessage: function(field) {
return Session.get('commentSubmitErrors')[field];
},
errorClass: function (field) {
return !!Session.get('commentSubmitErrors')[field] ? 'has-error' : '';
}
});

Template.commentSubmit.events({
'submit form': function(e, template) {
e.preventDefault();

var $body = $(e.target).find('[name=body]');
var comment = {
body: $body.val(),
postId: template.data._id
};

var errors = {};
if (! comment.body) {
errors.body = "Please write some content";
return Session.set('commentSubmitErrors', errors);
}

Meteor.call('commentInsert', comment, function(error, commentId) {
if (error){
throwError(error.reason);
} else {
$body.val('');
}
});
}
});
@@ -7,5 +7,11 @@
{{> commentItem}}
{{/each}}
</ul>

{{#if currentUser}}
{{> commentSubmit}}
{{else}}
<p>Please log in to leave a comment.</p>
{{/if}}
</div>
</template>
@@ -1,2 +1,25 @@
Comments = new Mongo.Collection('comments');

Meteor.methods({
commentInsert: function(commentAttributes) {
check(this.userId, String);
check(commentAttributes, {
postId: String,
body: String
});

var user = Meteor.user();
var post = Posts.findOne(commentAttributes.postId);

if (!post)
throw new Meteor.Error('invalid-comment', 'You must comment on a post');

comment = _.extend(commentAttributes, {
userId: user._id,
author: user.username,
submitted: new Date()
});

return Comments.insert(comment);
}
});

0 comments on commit 1f82c0a

Please sign in to comment.
You can’t perform that action at this time.