Firebase firestore in the forum application #15: Make form edit comment and Update comment

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Make form edit comment
  • Update comment

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

Let's continue our previous tutorial about forum applications using firebase. Before we have made the comment. In the previous tutorial, we have succeeded in creating a comment system that we have implemented in the forum application that we created. In previous tutorials we have also created a function for ownership of comments on each forum, we will only allow the comment edit feature of the comment owner. In this tutorial we will continue the feature, we will learn how to bring up the edit form and edit the comments.

Make form edit comment

The first thing we will do is create the edit form. here we will edit the comments whose form is not much different from the form for adding comments. In the previous tutorial, we have created a function to check the ownership of the forum. here's how it looks:

forum-detail.hbs

<div class="row">
    <div class="container" id="contain-comm">
        <h4>List comments</h4>
        {{#each replies}}
            {{data.desc}} by <b><i>{{data.user.name}}</i></b>
            <a href="#" class="btn btn-info is-hidden replies-btn" owner-id="{{data.user.user_id}}" onclick="editComment('{{id}}','{{data.desc}}')">Edit</a><br>
        {{/each}}
    </div>
</div>

In the code above we have created a function that is editComment () in this function I will pass two parameters. The first is the id {{id} from the subdocument collection replies and the second is the description {{data.desc}} or content of the comment. We pass it through the template, so we can see the results if we inspect the template page, like the following:

Screenshot_1.png

If we have rendered the template then we can see it rendered in the function above. Now that we have passed the data we need, now we can start creating the editComment() function.

  • Create interface edit form

Here we will create a frontend from the edit comment form, for those of you who have followed this tutorial you know that we already have a class = "hidden" which is used to Hidden elements, we use this class to hide elements that are not owned by the logged in user. This class is also what we will use to hide the edit form comments from users who do not have access to edit the comment. For more details, we can see the code below:

forum-details.hbs

<div class="is-hidden" id="updateForum">
    <div class="row">
        <div class="container">
            <div class="form-group">
                <textarea class="form-control col-md-6" id="comment" rows="3" placeholder="Your comment" style="margin-bottom:5px;"></textarea>
                <button type="button" class="btn btn-success" onclick="updateComment()">Update comment</button>
            </div>
        </div>
    </div>
</div>

Whats needs to be noticed in the template above is that we give class="is-hidden" and give id="updateForum". As I said before class = "is-hidden" will be used to hide elements that do not belong to the user who is logged in and here I addid = "updateForum" so that we can access the element to remove the is-hidden class.

Then if we look at the tag <textarea>. I add id="comment-desc" so that we can fill in the values from the text-area with the comments we will edit. then we can make the editComment () function.


  • Create editComment () function

After we pass the id document from the subcollection replies, then we will create the editComment () function. In this function we pass two parameters, namely the ID document and the contents of the comments, we need an ID document so we can edit the comments specifically. Later the parameters that we have passed in the editComment () function will become dynamic according to the contents of the comment For more details, we can see the code below:

function editComment(replyId, prevDes) {
    document.getElementById('comment-desc').value = prevDes;
    document.getElementById('updateForum').classList.remove('is-hidden');
}

In this function, we will accept repliyId and prevDes as parameters. because we will edit we have to give the edit form value with the previous value that we will update. here I will give a value in element id comment-desc with value from prevDes document.getElementById('comment-desc').value = prevDes;.

And then we will also delete the is-hidden class so that we can view the edit comment form we have made. if nothing goes wrong then we can see an example like the picture below:

ezgif.com-video-to-gif.gif

We can see in the picture above we have managed to get the description in the edit form, now we continue to update the comments we have made before.

  • Update comment

Here we will update the comments that we have edited, we need a replyId to update comments specifically, now how can we get a replyId on the updateComment () ?. We don't pass anything in the updateComment() function, but I will create a global variable to store the replyId when the user clicks the edit button available in each comment. For more details, we can see the code below:

var activeReplyId = '';
function editComment(replyId, prevDes) {
    activeReplyId = replyId;
    document.getElementById('comment-desc').value = prevDes;
    document.getElementById('updateForum').classList.remove('is-hidden');

}

I will create a global variable, namely var activeReplyId = ' ';, I gave the default value ' ' and then after the ediComment () function is run we will change the value to the replyId value activeReplyId = replyId;. Of course the replyId value is dynamic depending on the edit button clicked by the user.

  • Create new rules database for updates comment

Before we start updating the database in the replies subcollection, we will change the database rules to allow database updates, the following is an example:

rules forum-firebase

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read, create: if request.auth != null;
    }
    match /forums/{slug} {
      allow read;
      allow create: if request.auth != null 
                                && request.resource.data.title.size() > 10
      allow update: if request.auth.uid == resource.data.user.user_id
                                && request.resource.data.title.size() > 10
        match /replies/{reply} {
            allow read;
          allow create: if request.auth != null 
                                && request.resource.data.desc.size() > 20
                    allow update: if resource.data.user.user_id == request.auth.uid 
                                && request.resource.data.desc.size() > 20
        }
    }
  }
}

The above code is the rules of the database that we use in this forum application. The code we just added is

allow update: if resource.data.user.user_id == request.auth.uid 
                                && request.resource.data.desc.size() > 20

We add these rules at the URL match/replies/{reply}. At this URL we will allow the update method if the user is the same user as the user logged in resource.data.user.user_id == request.auth.uid.

Update comment

In this section we will update the comments that we have edited, we can see in the previous section we have defined the updateComment () function. Here we will make the function.

function updateComment() {
    var forumId = document.getElementById('forum_id').value;
    var newComment = document.getElementById('comment-desc').value;

    var dbRef = db.collection('forums').doc(forumId).collection('replies').doc(activeReplyId);

    dbRef.set({
        desc: newComment.replace("<br />","\n"),
        updated_at: new Date()
    },{merge:true})
    .then(function(res){
        location.reload()
    }).catch(function(err){
        console.log(err)
    })
}

To be able to update the data in the replies subcollection we need two accesses.
The first is the forum document or forum id and the second is the document for the replies. we can get both of these conditions in the following varible:

var forumId = document.getElementById('forum_id').value;
var newComment = document.getElementById('comment-desc').value;

After getting access to the document ID of each collection, we can create a reference database or database directory with that data. Like the following code:

db.collection('forums').doc(forumId).collection('replies').doc(activeReplyId);

-> Because replies are subcollections of the collection forums, then we have to access the forums first db.collection('forums').

-> After accessing the forum, we will access the document ID which is in the forum collection .doc(forumId). forumId is a variable whose value we get from the forum_id document.getElementById('forum_id').value;.

-> Then we will access the replies subcollection in the forums ID document .collection('replies') and then in the replies subcollection, we will access the document ID that we have stored in the global variable activeReplyId we have created in the previous section.

To update the data we can use references from the database that we have defined in the dbRefvariable as follows:

    dbRef.set({
        desc: newComment.replace("<br />","\n"),
        updated_at: new Date() 
})

We use the set function to update data and data that we update is desc and updated_at. We get desc from the latest comments that the user has edited we can get in the newComment variable var newComment = document.getElementById('comment-desc').value;.

If we succeed, we can update the comments we have in the database like the demonstration below:

ezgif.com-video-to-gif (1).gif

We can see in the picture above we have successfully updated the data contained in the subcollection of the replies, this means our comment update feature is running well. Hopefully useful, thank you.

Curriculum

  • Forum app

Firebase app#1, Firebase app#2, Firebase app#3, Firebase app#4, Firebase app#5, Firebase app#6, Firebase app#7, Firebase app#8, Firebase app#9, Firebase app#10,

Proof of work done

https://github.com/milleaduski/firebase-forum

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • Tutorial interesting and well explained, however it is necessary to improve the structure of the contribution.

  • Again, it's necessary to put brief comments in your code sections. Code comments help less-savvy readers better understand your lines of code

  • Your GIFs are very intuitive, good job!

  • Thanks for following some of our suggestions in your previous tutorials. We hope your next tutorial is better structured.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.032
BTC 60918.56
ETH 2919.11
USDT 1.00
SBD 3.56