Store HTML Controls in Database as JSON string or inside JSON File : NodeJs Example
BALWANT SINGH
Senior Associate Technology | Publicis Sapient | Microsoft Certified Developer
Here is the basic example that demos how you can store html controls in database or json files and render them inside html.
HTML Control as JSON Data
We can control our JSON files for each form that we want in our web application or we can store JSON data as string inside our database.
The following JSON contains some basic controls data related to student data like Name, Age, DOB, Gender etc. for this example we are storing it as controls.json in project directory.
领英推荐
{
"controls": [
{
"name": "studentName",
"type": "text",
"label": "Student Name",
"placeholder": "Enter student name",
"required": true
},
{
"name": "age",
"type": "number",
"label": "Age",
"placeholder": "Enter age",
"required": true
},
{
"name": "dob",
"type": "date",
"label": "Date of Birth",
"required": true
},
{
"name": "address",
"type": "text",
"label": "Address",
"placeholder": "Enter address",
"required": true
},
{
"name": "pinCode",
"type": "text",
"label": "Pin Code",
"placeholder": "Enter pin code",
"required": true
},
{
"name": "gender",
"type": "select",
"label": "Gender",
"options": ["Male", "Female", "Other"],
"required": true
},
{
"name": "mobileNumber",
"type": "tel",
"label": "Mobile Number",
"placeholder": "Enter mobile number",
"required": true
}]}
How to Render this Control using NodeJs
Here is the sample code how we can render these controls.
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
fs.readFile('controls.json', 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading JSON file');
return;
}
const controls = JSON.parse(data).controls;
let formHtml = '<form>'; controls.forEach(control => {
formHtml += <label for="${control.name}">${control.label}</label>;
if (control.type === 'text') {
formHtml += <input type="text" id="${control.name}" name="${control.name}" placeholder="${control.placeholder}" ${control.required ? 'required' : ''}>;
}
else if (control.type === 'select') {
formHtml += <select id="${control.name}" name="${control.name}" ${control.required ? 'required' : ''}>; control.options.forEach(option => {
formHtml += <option value="${option}">${option}</option>; }); formHtml += '</select>';
}});
formHtml += '<button type="submit">Submit</button></form>';
res.send(formHtml); }); }); app.listen(port, () =>
{
console.log(`App listening at https://localhost:${port}`);
});