61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
import API from './api.js';
|
|
import { entitiesConfig } from './entitiesConfig.js';
|
|
|
|
export function generateForm(entityType, formContainerId) {
|
|
const config = entitiesConfig[entityType];
|
|
const formContainer = document.getElementById(formContainerId);
|
|
formContainer.innerHTML = ''; // clear existing content
|
|
|
|
const form = document.createElement('form');
|
|
config.fields.forEach(field => {
|
|
const label = document.createElement('label');
|
|
label.setAttribute('for', field.name);
|
|
label.textContent = `${field.name.charAt(0).toUpperCase() + field.name.slice(1)}:`;
|
|
|
|
const input = document.createElement('input');
|
|
input.type = field.type;
|
|
input.name = field.name;
|
|
input.id = field.name;
|
|
if (field.required) input.required = true;
|
|
|
|
form.appendChild(label);
|
|
form.appendChild(input);
|
|
form.appendChild(document.createElement('br'));
|
|
});
|
|
|
|
const submitButton = document.createElement('button');
|
|
submitButton.type = 'submit';
|
|
submitButton.textContent = 'Submit';
|
|
|
|
form.appendChild(submitButton);
|
|
formContainer.appendChild(form);
|
|
|
|
form.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const formData = new FormData(form);
|
|
const formDataObject = {};
|
|
formData.forEach((value, key) => {
|
|
formDataObject[key] = value;
|
|
});
|
|
|
|
try {
|
|
await API.post(`${entityType}`, formDataObject);
|
|
form.reset();
|
|
showNotification('Entity created successfully');
|
|
} catch (error) {
|
|
showNotification(`Error: ${error.message}`, 'error');
|
|
}
|
|
});
|
|
}
|
|
|
|
function showNotification(message, type = 'success') {
|
|
const notification = document.createElement('div');
|
|
notification.className = `notification ${type}`;
|
|
notification.textContent = message;
|
|
|
|
document.body.appendChild(notification);
|
|
|
|
setTimeout(() => {
|
|
notification.remove();
|
|
}, 3000);
|
|
} |