我对此深感困惑,我什至无法提出一个明智的问题,但是这里...
我的表格很庞大(有时会更改)。我找到了一种合理的方法来从表单获取所有数据,将其转换为对象,然后一次将其保存到Firebase。看起来像这样,并且工作正常(我认为):
const incidentReport = document.getElementById('incident-report-form');
let irv = {};
// This works. All form data is saved to an object (as required by firebase), with the question as the name and the answer as the value.
incidentReport.addEventListener('submit', (e) => {
e.preventDefault();
[...incidentReport.elements].forEach((item) => {
let name = item.name;
let value = item.value;
irv = { ...irv, [name]: value };
});
// After all data is collected in one object, I send it to the database all at once.
db.collection('incident reports').add(irv);
});
好的,到目前为止,很好...现在,我想将其从数据库中取出(我知道如何执行此操作),然后重新填充相同的表单(不知道)。我100%陷入困境,我什至不知道该怎么做。
如果这很容易,并且我的大脑刚刚关闭,请原谅我...这是艰难的一天。 预先感谢。
编辑-这似乎有用吗?我仍然很乐意接受批评和/或改进。
// Get data from incident reports
//@TODO -> Need to create a list of incident reports, and then load the one //the user clicks on.
//Right now there is only one incident report in the database for testing.
db.collection('incident reports')
.get()
.then((snap) => {
snap.docs.forEach((element) => {
data = element.data(); //Previously declared but not included in this snippet, sorry.
});
for (let [key, value] of Object.entries(data)) {
let x = document.getElementsByName(key)[0];
if (x !== undefined) {
x.value = value;
}
}
});
答案 0 :(得分:1)
如果我对它的理解正确,那么一旦您从Firestore集合中返回了数据,就希望将其以HTML形式打印回去。考虑到这一点,您应该不难实现这一目标。
一旦将文档加载到数组中,就应该能够将值分配给变量,这些变量将以表格形式打印。应该是这样的:
//Getting the collection and a specific document
var report = db.collection('incident reports').doc('<report>');
var getDoc = report.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
// Loading the values of the document into variables
var name = getDoc.data().name;
var value = getDoc.data().value;
...
// Other values loaded to other variables that you create
}
})
.catch(err => {
console.log('Error getting document', err);
});
将值加载到变量中后,只需创建标记<script>
,它将通过Java脚本将值添加到HTML中。看起来可能像这样:
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
document.getElementById('<form item name>').innerHTML = name;
</script>
虽然此代码未经测试,但我认为这对您来说是实现目标的良好起点。它仅用于一个文档,但是由于您现在正在测试中并且只有一个文档,因此应该没问题。
除此之外,您可以在此另一篇文章中找到有关如何从Firestore检索值并在页面中进行定价的一个很好的完整示例:How can I display all data from Firestore documents into html elements
让我知道信息是否对您有帮助!