Firebase firestore in the forum application #6: Forums collection and Add data in collection

in #utopian-io5 years ago (edited)

Repository

https://github.com/firebase

What Will I Learn?

  • Forums collection
  • Add data in collection forums

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a series of Forum application tutorials using Firebase, in this application we have accomplished many things, one of which is the auth method with social media. Well, my tutorial this time we will be included in the discussion of making the forum application. So for those of you who haven't followed this tutorial before, I suggest you follow the curriculum below:

Create a forum

Well, this is the big title of this tutorial, but I will share it. previously we have learned about the Firestore cloud database and have made collections and documents on the database. The first part that will be created is to add a forum to the application that we created. For that we need a few steps as below:

  • Create an add forum interface

To create a forum application, we will start by creating an interface so that users can interact with the applications we make. here I will use the bootstrap framework for CSS to make it easier for us to do styling. For more details, we can see in the example below:

home.hbs

<form>
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" id="title" placeholder="Your tittle">
    </div>
    <div class="form-group">
        <label for="desc">Desciptions</label>
        <textarea class="form-control" id="desc" rows="3"></textarea>
    </div>
    <button class="btn btn-info" onclick="addTopic()">Add topic</button>
  </form>

We can see in the example above we already have a form that consists of title and description and on this form, we will have a button that will be used to add form data to the database firestore that we already have.

On that button I will add a function that is addTopic () which will be used to add data. The following is the display of the interface that we created above:

Screenshot_11.png

We can see above is a simple display of our forum interface, now our next task is to save from the form to the Firestore database.

  • Create forums collections

The next task is to add a forum, to add a forum we will create a new collection. In this collection of forums, we will add new fields. The following is a key that we will enter into the collection forums:

title: The title is the title of the forum that we will create. The data type is string.

slug: Slug is the title that we have generated into a slug by changing the space ( ) to (-). Example: this-is-slug. We will use this slug as the path of the forum that we access. the data type is string.

desc: desc is a description of our forum, the data type is a string

user: The user is the data user who created the forum, here will use the id as something unique and represent one user.

created_at: created_at is the time when the forum was created, this is one of the important information in each forum.

updated_at: updated_at is the time when the forum was edited or updated.

Now we will make the collection in the firebase console.

ezgif.com-video-to-gif.gif

We can see in the picture above that we have successfully created the forums, now then we will use our form to store the data on the collection forums.

  • Rules in forums collection

Well, we have created a collection forums, now what we are going to do is add rules to the collection, as I said in the previous section we will use the slug method on the URL as a marker of a forum that we are going to later. the following are the rules.

Screenshot_1.png

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read, create: if request.auth != null;
    }
        //Rules for forums collection
    match /forums/{slug} {
      allow read;
      allow create: if request.auth != null 
                                && request.resource.data.title.size() > 10
    }
  }
}

In the rules forums we will use the parameter {slug}, the rules are that everyone can read allow read;

and we will learn to make new rules that we will require that the title must be greater than 10 characters. we can do it in the following way request.resource.data.title.size() > 10 and we also need the user to log in when they want to create a forum if request.auth != null.

  • Add forums to database firestore

Well, now we are done with the database and rules. Now we will use the database to store the data in our forum application. continuing the section above we already have the interface and form sections that have been provided. Now we will make the addTopic () function in our code as follows:

js/auth.js

function addTopic() {
    var title  = document.getElementById('title').value // get value from iinput title
    var desc = document.getElementById('desc').value  // get value from input textarea
    var slug = title.toLowerCase().replace(/[^\w]+/g, '').replace(/ +/g,'-')

    db.collection('forums').add({
        title: title,
        slug: slug,
        desc: desc.replace("<br />", "\n"),
        created_at : new Date(),
        updated_at : new Date()
    }).then(function(docRef){
        alert("The forum was successfully created")
    }).catch(function(err){
        alert("There was an error adding the forum")
    })
}

We will start collecting data that we need one by one to be saved in the collection forums:

title: We can get the value from the title from the input title that is on the form we have made above document.getElementById('title').value.'title' is an ID in the input title id = 'title'.

desc: We can also get a description of the forum via the textarea input we have given id = 'desc'. to get the valuation we can do it like the following document.getElementById('desc').value.

slug: as I said before the slug is the result of the title generated. So we will replace all the separating characters in the title (-). Here is the regrex syntax to change the title to slug title.toLowerCase().replace(/[^\w]+/g, '').replace(/ +/g,'-').

created_at: created_at is the time the forum was created, so I will use the current time new Date()

updated_at: updated_at is the time when the forum is edited and updated, so for the first time it is created we will add time now new Date().

The add () function is a promise so we can use then to accept the response when the process is successful.then(function(docRef){ } and we can catch the error value when the process fails .catch(function(err){}


Now we have collected the data we need to store in the database. now we will save it in the collections forums, like the example below:

db.collection('forums').add({
        title: title,
        slug: slug,
        desc: desc.replace("<br />", "\n"),
        created_at : new Date(),
        updated_at : new Date()
})

To save the database we must use an instance of var db = firebase.firestore ();. After getting an instance of the database we can use the collection forums db.collection('forums').add({ }). to add it we can use add() function and data in function that we will fill in object {} form.

Screenshot_2.png

Well now that we have succeeded in making collections and collecting data to add to the collection of forums, the following is the demonstration:

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

we can see in the picture above, we have succeeded in creating a collection forum and successfully added data in the collection, here we have succeeded in making the forum application have a new feature which is adding forums

Curriculum

  • Forum app

Firebase app#1, Firebase app#2, Firebase app#3, Firebase app#4, Firebase app#5

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:

  • Nice work on the explanations of your code, although adding a bit more comments to the code can be helpful as well.

  • In the sections of your code please ident the code.

-Thanks for following some suggestions given in the previous 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.30
TRX 0.12
JST 0.033
BTC 64400.33
ETH 3140.71
USDT 1.00
SBD 3.93