Create a system admin panel using Firebase #2 : Use firebase.database and Add child data in realtime database

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Use firebase.database
  • Add child data in real-time database

Requirements

  • Basic HTML, CSS, and javascript
  • Use firebase
  • Local server (Xampp, Wampp, or etc)

Resources

Difficulty

Basic

Tutorial Content

This tutorial will continue the previous tutorial series about making the admin panel use firebase. So I suggest you follow the tutorial before. Because there are several project initializations and basic project creation there and we have loaded a user login system that will act as an admin. Well in this tutorial, we will upgrade the features in our admin panel. we just start this tutorial.

Make real-time database

In the admin system, we will create features such as blogs, which will give users the rules admin who can add, edit or delete data on the blog. For that first step, we have to do is create a table in our firebase database.

  • Make data in real-time database

In this application, we will use the real-time database in Firebase. unlike most databases like Mysql, Postgres or etc. In a real-time database, we do not have relations between tables or data types used. We only need to add data like JSON which consists of keys and values. The following is how to add data to our real-time database.

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

The example above is how to manually add data to our Firebase dashboard. what we will do is programmatically add data.

  • Create a form for input data

Before we add data to our blog, we will add a simple input form to the application that we created. for more details, we can see examples like the following:

Form input

<div id="inputdata">
      <h3>Input Form</h3>
      <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" id="title" autocomplete="off">
      </div>
      <div class="form-group">
        <label for="desc">Description:</label>
        <input type="text" class="form-control" id="desc">
      </div>
      <button id="btnAddData" class="btn btn-primary">Add</button>
</div>

We will create a simple data input form with input title <input type="text" class="form-control" id="title" autocomplete="off"> and Description input <input type="text" class="form-control" id="desc">

Initialization element

We have created a form of input on our application, now we will initialize it in javascript. We can initialize it like the following:

    var formLogin = document.getElementById('login');
  var formInput = document.getElementById('inputdata');



Handle page login

We will create a page that will change when the user is logged in, so later we will display the input form only when the user is logged in. We can handle it through the on AuthStateChanged () function provided by firebase.auth.

 //status user
  auth.onAuthStateChanged(function(user){
        if(user) {
            //do everthing if user exist.
            //this means the user is logged in 
            btnLogout.classList.remove('hidden');
            btnLogin.classList.add('hidden');
        formLogin.classList.add('hidden');
        formInput.classList.remove('hidden');
            
        } else {
            //do everthing if user exist.
            //this means the user is logged in 
            btnLogout.classList.add('hidden');
            btnLogin.classList.remove('hidden');
        formLogin.classList.remove('hidden');
        formInput.classList.add('hidden');
        }
  })
  • We initialized the login form element as formInput var formInput = document.getElementById('inputdata');.

  • We can show the input form when the user is logged in formInput.classList.remove('hidden'); and hide the input form when the user is not logged in formInput.classList.add('hidden');. We can see the results like the following:

ezgif.com-video-to-gif.gif

We can see in the picture above when the user is logged in, the login form disappears and the data input form appears. This is according to what we want. then we will learn how to input data in the Firebase real-time database.


Add data in realtime database

  • Initialization firebase.database ()

Now we will learn how to enter data in the realtime database. the thing we have to pay attention to is to do the initialization firebase.database (). For more details, we can see the code below:

 var database  = firebase.database();
 var blogsRef  = database.ref('blogs');
  • var database = firebase.database(); to access the database that is in firebase, we need to initialize firebase.database ().
  • var blogsRef = database.ref('blogs'); After we initialize firebase.database() we can use it to access the table references we will use. Reference is like a table if on mysql. In this tutorial, the reference table names are 'blogs', you can see the table on your database dashboard in the firebase console.
    Screenshot_7.png

  • Preparing input elements

We have the data input form that we will do next is to initialize the element in javascript. We can see examples like the following:

  var title       = document.getElementById('title');
  var desc        = document.getElementById('desc');
  var btnSubmit   = document.getElementById('btnAddData');

We can initialize it as usual with doument.getElementById('id').

  • Add data

After initializing the element, we can now add data to our realtime database. at the top we have defined <button id="btnAddData" class="btn btn-primary">Add</button> as btnSubmit = document.getElementById('btnAddData');. so we can use events in btnSubmit. For more details, we can look at the code below:

btnSubmit.addEventListener('click', function(){
    blogsRef.push({
      title : title.value,
      desc : desc.value
    })

    title   = ' ';
    desc    = ' ';
});

blogsRef.on('child_added', addData);

  function addData() {
    alert("Data successfully added");
  }
  • We put the onclick event on btnSubmit, so later when clicked it will run the function inside it btnSubmit.addEventListener('click', function(){}).

  • We have defined which references we will use, that is var blogsRef = database.ref ('blogs');. So we can use the blogsRef variable as a reference.

  • The most important thing when adding data is that we use the push() method and data in the form of objects that contain keys and values like this:

 blogsRef.push({
      title : title.value,
      desc : desc.value
 })

title is the key and title.value is the value we get from the value that the user input.
desc is the key and desc.value is the value we get from the value that the user input.

  • Event on('child_added')

We can also install events when data is successfully entered, you can do whatever you want when the data is successfully stored in the database. We can use the "child_added" event. In the second parameter, we can run a function. In this tutorial, I run theaddData() function and in that function, I just display alert ().

  function addData() {
   alert("Data successfully added");
  }

After all, is done we can test whether the program we are making runs well. the following is a demonstration of the program:

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

as we saw above we have successfully added data in our real-time database that is in firebase. We have also learned how to listen to events when data is successfully added. thank you for following this tutorial. I hope this tutorial can give you an idea of how to use the real-time database in Firebase. See you in the next tutorial...

Curriculum

Create a system admin panel using Firebase #1 : initialization, user admin settings, and authentication user admin

Proof of work done

https://github.com/milleaduski/firebaseAdminPanel

Sort:  

Thank you for your contribution @duski.harahap.

  • We really like the animations to exemplify what they have been developing. Good job.

  • We suggest that the title be shorter and that it contains the key words about what it will explain.

Your tutorial is interesting and pretty basic for those who do not know the firebase. Thank you for sharing your knowledge.

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? Write a ticket on https://support.utopian.io/.
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.35
TRX 0.12
JST 0.040
BTC 70884.24
ETH 3570.27
USDT 1.00
SBD 4.76