Firebase firestore in the forum application #11: Form edit forum and Update data forum by duski.harahap

View this thread on steempeak.com
· @duski.harahap ·
$20.96
Firebase firestore in the forum application #11: Form edit forum and Update data forum
#### Repository
https://github.com/firebase

#### What Will I Learn?
- Form edit forum
- Update data forum

#### Requirements
- Basic Javascript
- Install Firebase


#### Resources
- Firebase-https://firebase.google.com/

#### Difficulty
Basic

### Tutorial Content

In this tutorial, I will continue the previous tutorial series. This tutorial I will use the edit form to edit the forum that we have created. with the system, we have created [before](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-10-authorized-domain-and-user-forum-ownership-1560338464527) we can ensure that the forum can only be edited by the owner of the forum. For those of you who are just following this tutorial, there are several series that you should follow first so that you don't have problems following this tutorial.

### Form edit forum

In this section we will use the form to edit the forum, here I will use ***bootstrap***. In bootstrap, I will use the form-input component. The following is the display of the interface:

**forum-details.hbs**

```
<div class="is-hidden">
	<form>
	  	<div class="form-group">
		    <label for="title">Title</label>
		    <input type="text" class="form-control" id="title" value="{{forum.title}}">
	  	</div>
	  	<div class="form-group">
		    <label for="desc">Desciptions</label>
		    <textarea class="form-control" id="desc" rows="3">{{forum.desc}}</textarea>
	  	</div>
	  	<button class="btn btn-info" type="button" name="button" onclick="editTopic()" id="update-btn">Update</button>
	</form>
</div>
<script type="text/javascript" src="/assets/js/auth.js"></script>
</body>
<style type="text/css">
	.is-hidden {
		display: none;
	}
</style>
```

We have passed the object ***forum*** section in the **forum-details.hbs** template. Now we can use it to fill in the edit form with the **value** of the ***forum*** object.

We will make an **input text** for the *title* ```<input type="text" class="form-control" id="title" value="{{forum.title}}">``` and the value will be taken from the ```forum.title``` object.

And then we will fill in the description with the textarea ``` <textarea class="form-control" id="desc" rows="3">{{forum.desc}}</textarea>```. WWe get the value from ```forum.desc```.

If you followed the previous tutorial you would know that we have a class that is used to hide elements from users who are not forum owners ```<div class="is-hidden">```.

- **Edit forum with ownership access**

We can see in the form we will make the element form hidden by default. We will change the situation if the user who is logged in is the user who owns the forum. We will add a ***onclick*** function to the edit button, for more details we can see in the code below:

**forum-details.hbs**

```
<h2>Forum {{forum.title}}</h2>
	<p>{{forum.desc}} <span><i>by: <b>{{forum.user.username}}</b></i></span></p>
	<input type="hidden" name="owner_uid" id="owner_id" value="{{forum.user.user_id}}">
	<a href="#" class="btn btn-info is-hidden" id="btn-edit" onclick="showEditForm()">Edit</a>
```

The function that I will use above is ```showEditForm ()```. We will use this function to display the edit form. now we will make the function like the code below.

```
<script type="text/javascript">
	

function showEditForm() {
	document.getElementById('editForm').classList.remove('is-hidden')
}
</script>
```

The function above is quite simple, we will only remove the ***is-hidden*** *class* in the edit form element. **editForm** is an ***id*** from form edit element, we can give the id like this:
```
<div class="is-hidden" id="editForm"></div>
```

We can see the results from the form edit interface as shown below:

![Screenshot_3.png](https://ipfs.busy.org/ipfs/QmVnSJ1i6i1xtMX4W9kWx2ptWCfaj8oUv9b9uLGcGSK2Ef)

We can see in the picture above, the input from the form ***has been filled*** in from the object forum that we have passed in the **forum-details.hbs** template.

The edit button only ***appears*** in the owner of the forum, so other users ***can not edit*** the forum that is not theirs, as we can see in the demonstration below:

![ezgif.com-video-to-gif.gif](https://cdn.steemitimages.com/DQmfXpkaDyFhqGAyLEStcV4AVe77rQaG2gVe2hPHJSU6w1c/ezgif.com-video-to-gif.gif)

You can see in the picture above there is a forum that cannot bring up the edit button because the forum is not his. until here our forum ownership system has been successful.


### Update data forum

We have created a form to edit the data, and then we will learn how to update data in the application of our Firebase forum. We have created a form to edit the data. For those of you who are just following this tutorial for information that in this tutorial we use Firestore as the database if you don't know what firestore is you can see my previous tutorial in the **curriculum** section.
<br>
- **Create new rules for update data**

We will start to make the data update feature by creating new rules on our Firestore database, here we will create a rule for updates, here is an example:

```
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
    }
  }
}
```

![Screenshot_4.png](https://ipfs.busy.org/ipfs/Qma7nRGvpf51WyUmSSfJaWm4EQVMB5g4toFtR3EnKTrhDt)

Here I add for the update section, in the update section we only allow updates when ```request.auth.uid == resource.data.user.user_id```. This means that the user ID must be the same as user_id in the Firestore database because we will guarantee that the person who can edit the forum is the owner of the forum.
<br>
- **Update data forum**

Now that we have completed the rules in the database, now we will update the data in the forum. Forum data stored in the database is in a document and the name of the document is the name that was automatically generated by ***Firebase***. For more details, we can see in the picture below:

![Screenshot_5.png](https://ipfs.busy.org/ipfs/QmfDgC554FqutZvQVCvLgk1fhb51xzYU3zzHxQHu23edvJ)

We need the **document ID** to update the data in the document. * than where can we get the ID?*

We can get the id when we draw the *single forum* data at the ```app.getURL('/ forum /: slug', function (req, res) { }```.

**index.js**
```
db.collection('forums').where('slug', '==', req.params.slug).get()
	.then(snapshot => {
		snapshot.forEach(doc => {
			forum = doc.data()
			console.log(doc.id)
		})
		res.render('forum-detail', {forum:forum})
	}).catch(err => {
		console.log(err)
	})
```

I will do a ```console log()``` on doc which is the response we received when pulling single forum data.

![Screenshot_6.png](https://ipfs.busy.org/ipfs/QmXf77Dez8HGGpnp22Tw1B4JpVdZCqiA6qRRvLy4MrJdUu)

We see in the picture above we managed to get the document ID we need. We can get the id on the key id on the doc object. now *we will pass the **ID** to the **frontend***.

**index.js**
```
db.collection('forums').where('slug', '==', req.params.slug).get()
	.then(snapshot => {
		snapshot.forEach(doc => {
			forum = doc.data()
			forum.id = doc.id
		})
		res.render('forum-detail', {forum:forum})
	})
```

I will pass the value to the object ***forum*** with the key ***id*** ```forum.id = doc.id```. now we will render the id as a parameter to the ```updateForum()``` function. We will render the id like in the example below:

**forum-details.hbs**

```
<form>
			  	<div class="form-group">
				    <label for="title">Title</label>
				    <input type="text" class="form-control" id="title" value="{{forum.title}}" placeholder="Your tittle">
			  	</div>
			  	<div class="form-group">
				    <label for="desc">Desciptions</label>
				    <textarea class="form-control" id="desc" rows="3">{{forum.desc}}</textarea>
			  	</div>
			  	<button class="btn btn-info" type="button" name="button" id="update-btn" onclick="updateForum('{{forum.id}}')">Update</button>
			</form>
```
We will create a function and will make the document id as a parameter so we can update the forum according to the forum we are editing ```onclick="updateForum('{{forum.id}}')"```.

![Screenshot_7.png](https://ipfs.busy.org/ipfs/QmWHfZoSyeexA5R4FjAZECPoKki9Jpah3CHuG4MQEXUBPn)
<br>

- **Create function ```updateForum()```**

In the ```updateForum()``` function, I will receive the **document id** parameter that will be used to access documents in our database, so that we can update the data according to the forum that we are updating. The following is an example of a forum update:


```
function updateForum(id) {
	db.collection('forums').doc(id).set({
		title : document.getElementById('title').value
		desc : document.getElementById('desc').value
		updated_at : new Date()
	}, {merge : true})
	.then(function(){
		location.reload()
	}).catch(function(err){
		console.log(err)
	})
}
```

In this function, we will use a ***instance*** of the firebase firestore that we have defined in a var variable ```db = firebase.firestore ();``` and then we can access the collection of ***forums***. then using the parameters that we have passed in this function to access the document we are editing.

For the value values from our forum we can get it from the input form we have created with each id. For the **title** we can get the value from ```document.getElementById('title').value```. For the **desc** we can get the value from ```document.getElementById('desc').value```.

**title and desc** are ***keys*** or fields in the Firestore database. It *should* be noted that the key must be the same as the database, otherwise, an error will occur, firestore will not recognize the field. If all the steps work well, then we can see the results as in the demonstration below:

![ezgif.com-video-to-gif (1).gif](https://cdn.steemitimages.com/DQmZJhBU5cZsdJZUdKrJqvB9GexAhXGcS4p1PRtmCqwxfEJ/ezgif.com-video-to-gif%20(1).gif)

![Screenshot_8.png](https://ipfs.busy.org/ipfs/QmQ7FMyksSicV57PqVDqrkoXrKCcL5Nv6hxVwbUhTDVLLc)

Well, we can see the result that we have successfully updated the data that is on the **Firestore database**. We have updated the title and desc also updates the update time. Until here is our tutorial, hopefully, you will benefit from this tutorial, thank you.


### Curriculum

- **Forum app**

[Firebase app#1](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-1-firebase-init-and-cloud-backend-function-1557758217688), [Firebase app#2](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-2-local-server-routing-and-template-login-gmail), [Firebase app#3](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-3-logout-function-and-login-with-facebook-account), [Firebase app#4](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-3-logout-function-and-login-with-facebook-account), [Firebase app#5](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-4-create-apps-and-login-with-a-twitter-account-1558448308709), [Firebase app#6](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-6-forums-collection-and-add-data-in-collection-1559196649948), [Firebase app#7](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-7-store-user-data-in-forums-and-firebase-admin-1559372598705), [Firebase app#8](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-8-fetch-data-from-collection-and-render-data-cloud-function-1559462309843), [Firebase app#9](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-9-implement-slug-as-url-params-and-single-app-forum), [Firebase app#10](https://steemit.com/utopian-io/@duski.harahap/firebase-firestore-in-the-forum-application-10-authorized-domain-and-user-forum-ownership-1560338464527), 


#### Proof of work done

https://github.com/milleaduski/firebase-forum
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 8 others
properties (23)
post_id76,389,241
authorduski.harahap
permlinkfirebase-firestore-in-the-forum-application-11-form-edit-forum-and-update-data-forum-1560522053217
categoryutopian-io
json_metadata{"app":"steeditor\/0.1.2","format":"markdown","image":["https:\/\/ipfs.busy.org\/ipfs\/QmXf77Dez8HGGpnp22Tw1B4JpVdZCqiA6qRRvLy4MrJdUu","https:\/\/ipfs.busy.org\/ipfs\/QmVnSJ1i6i1xtMX4W9kWx2ptWCfaj8oUv9b9uLGcGSK2Ef","https:\/\/cdn.steemitimages.com\/DQmfXpkaDyFhqGAyLEStcV4AVe77rQaG2gVe2hPHJSU6w1c\/ezgif.com-video-to-gif.gif","https:\/\/ipfs.busy.org\/ipfs\/Qma7nRGvpf51WyUmSSfJaWm4EQVMB5g4toFtR3EnKTrhDt","https:\/\/ipfs.busy.org\/ipfs\/QmfDgC554FqutZvQVCvLgk1fhb51xzYU3zzHxQHu23edvJ","https:\/\/ipfs.busy.org\/ipfs\/QmXf77Dez8HGGpnp22Tw1B4JpVdZCqiA6qRRvLy4MrJdUu","https:\/\/ipfs.busy.org\/ipfs\/QmWHfZoSyeexA5R4FjAZECPoKki9Jpah3CHuG4MQEXUBPn","https:\/\/cdn.steemitimages.com\/DQmZJhBU5cZsdJZUdKrJqvB9GexAhXGcS4p1PRtmCqwxfEJ\/ezgif.com-video-to-gif%20(1","https:\/\/ipfs.busy.org\/ipfs\/QmQ7FMyksSicV57PqVDqrkoXrKCcL5Nv6hxVwbUhTDVLLc"],"tags":["utopian-io","tutorials","firebase","web"],"users":["duski"],"links":["https:\/\/github.com\/firebase","https:\/\/firebase.google.com\/","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-10-authorized-domain-and-user-forum-ownership-1560338464527","https:\/\/cdn.steemitimages.com\/DQmZJhBU5cZsdJZUdKrJqvB9GexAhXGcS4p1PRtmCqwxfEJ\/ezgif.com-video-to-gif%20","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-1-firebase-init-and-cloud-backend-function-1557758217688","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-2-local-server-routing-and-template-login-gmail","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-3-logout-function-and-login-with-facebook-account","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-4-create-apps-and-login-with-a-twitter-account-1558448308709","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-6-forums-collection-and-add-data-in-collection-1559196649948","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-7-store-user-data-in-forums-and-firebase-admin-1559372598705","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-8-fetch-data-from-collection-and-render-data-cloud-function-1559462309843","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/firebase-firestore-in-the-forum-application-9-implement-slug-as-url-params-and-single-app-forum","https:\/\/github.com\/milleaduski\/firebase-forum"]}
created2019-06-14 14:21:00
last_update2019-06-14 14:21:00
depth0
children4
net_rshares37,101,625,753,837
last_payout2019-06-21 14:21:00
cashout_time1969-12-31 23:59:59
total_payout_value15.754 SBD
curator_payout_value5.207 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length12,266
author_reputation60,101,995,119,153
root_title"Firebase firestore in the forum application #11: Form edit forum and Update data forum"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout100,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (72)
@portugalcoin ·
$12.77
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.

- You have sections of code that aren't indent. Be careful to indent the code.

- Don't mix using the first person in your text and then the third person. Be consistent and always use the third person in your text.

- Try to improve the structure of your tutorial.

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](https://join.utopian.io/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](https://review.utopian.io/result/8/2-1-3-1-1-3-2-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
post_id76,402,058
authorportugalcoin
permlinkpt3rwa
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["duski.harahap"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/2-1-3-1-1-3-2-3-","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"],"app":"steemit\/0.1"}
created2019-06-14 19:09:45
last_update2019-06-14 19:09:45
depth1
children1
net_rshares21,965,847,544,275
last_payout2019-06-21 19:09:45
cashout_time1969-12-31 23:59:59
total_payout_value9.722 SBD
curator_payout_value3.052 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length1,050
author_reputation214,343,891,436,406
root_title"Firebase firestore in the forum application #11: Form edit forum and Update data forum"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (30)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id76,492,703
authorutopian-io
permlinkre-pt3rwa-20190616t193514z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-06-16 19:35:15
last_update2019-06-16 19:35:15
depth2
children0
net_rshares0
last_payout2019-06-23 19:35:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length64
author_reputation152,913,012,544,965
root_title"Firebase firestore in the forum application #11: Form edit forum and Update data forum"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
post_id76,403,381
authorsteem-ua
permlinkre-firebase-firestore-in-the-forum-application-11-form-edit-forum-and-update-data-forum-1560522053217-20190614t194723z
categoryutopian-io
json_metadata{"app":"beem\/0.20.19"}
created2019-06-14 19:47:24
last_update2019-06-14 19:47:24
depth1
children0
net_rshares0
last_payout2019-06-21 19:47:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length292
author_reputation23,203,609,903,979
root_title"Firebase firestore in the forum application #11: Form edit forum and Update data forum"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id76,406,329
authorutopian-io
permlinkre-firebase-firestore-in-the-forum-application-11-form-edit-forum-and-update-data-forum-1560522053217-20190614t213626z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-06-14 21:36:27
last_update2019-06-14 21:36:27
depth1
children0
net_rshares0
last_payout2019-06-21 21:36:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length595
author_reputation152,913,012,544,965
root_title"Firebase firestore in the forum application #11: Form edit forum and Update data forum"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000