Skip to content

Commit 2379342

Browse files
committed
Added: form lookups in get_form_html (#279) (#280)
1 parent 7388514 commit 2379342

File tree

4 files changed

+427
-34
lines changed

4 files changed

+427
-34
lines changed

libreforms_fastapi/app/templates/create_form.html.jinja

+118-1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,124 @@
3131

3232
{% block scripts %}
3333
<script>
34+
35+
var apiKey = "{{ request.user.api_key }}";
36+
function getLookup(formName, fieldName, el) {
37+
38+
// Access the selected option
39+
var selectedOption = el.options[el.selectedIndex];
40+
41+
// Get the 'data-hidden' attribute from the selected option
42+
var documentData = selectedOption.getAttribute('data-hidden');
43+
var documentId = selectedOption.value;
44+
console.log(documentData);
45+
46+
const contentField = document.getElementById(`content_${fieldName}`);
47+
48+
// Clear previous contents
49+
contentField.innerHTML = '';
50+
51+
if (documentData) {
52+
let dataObj;
53+
try {
54+
dataObj = JSON.parse(documentData);
55+
} catch (error) {
56+
console.error("Parsing error:", error);
57+
return; // Stop execution if JSON is invalid.
58+
}
59+
60+
const listGroup = document.createElement("div");
61+
listGroup.className = 'list-group';
62+
63+
Object.keys(dataObj).forEach(function(key) {
64+
const listItem = document.createElement("a");
65+
listItem.className = 'list-group-item list-group-item-action';
66+
listItem.innerHTML = `<strong>${key}:</strong> ${dataObj[key]}`;
67+
listGroup.appendChild(listItem);
68+
});
69+
70+
contentField.appendChild(listGroup);
71+
72+
let oldLink = document.getElementById('lookup-link-'+fieldName);
73+
if (oldLink) {
74+
oldLink.parentNode.removeChild(oldLink);
75+
}
76+
77+
// Create an anchor element with the appropriate href
78+
let link = document.createElement('a');
79+
link.href = "/ui/form/read_one/" + formName + "/" + documentId;
80+
link.innerHTML = "Open Full Record for this Form";
81+
link.className = "btn btn-primary d-flex justify-content-center my-3";
82+
link.title = "Click here to view more details about this form.";
83+
link.target = "_blank";
84+
link.setAttribute("aria-label", "View full details for this form");
85+
link.id = 'lookup-link-'+fieldName; // Add this line to set the id
86+
87+
contentField.parentNode.insertBefore(link, contentField);
88+
89+
90+
}
91+
}
92+
93+
94+
function generateLookup(formName, fieldName, displayFields) {
95+
96+
function fetchData(formName) {
97+
return new Promise((resolve, reject) => {
98+
$.ajax({
99+
url: `/api/form/read_all/${formName}?flatten=true&exclude_journal=true&stringify_output=true&sort_by_last_edited=true&newest_first=true`,
100+
type: "GET",
101+
dataType: 'json',
102+
beforeSend: function(xhr){xhr.setRequestHeader('X-API-KEY', apiKey);},
103+
success: function(formData) {
104+
resolve(formData.documents);
105+
},
106+
error: function(xhr, status, error) {
107+
reject(error);
108+
}
109+
});
110+
});
111+
}
112+
113+
// Fetch data for the single form
114+
fetchData(formName).then(documents => {
115+
116+
// First add an empty option at the top of the list
117+
$('#' + fieldName).append($('<option>', {
118+
value: "",
119+
'data-hidden': "",
120+
text: ""
121+
}));
122+
123+
124+
var trimmedData = [];
125+
// Process documents
126+
documents.forEach(form => {
127+
// Initialize an empty string for each form
128+
let concatenatedFields = '';
129+
130+
displayFields.forEach(field => {
131+
if (form[field] !== undefined) {
132+
concatenatedFields += form[field] + ', ';
133+
}
134+
});
135+
136+
// Trim the trailing commas and spaces, and add the concatenated string to the trimmedData array
137+
concatenatedFields = concatenatedFields.replace(/,\s*$/, '');
138+
trimmedData.push(concatenatedFields);
139+
140+
// Append each concatenated string as an option to the select element
141+
$('#' + fieldName).append($('<option>', {
142+
value: form['__metadata__document_id'],
143+
'data-hidden': JSON.stringify(form),
144+
text: concatenatedFields
145+
}));
146+
});
147+
}).catch(error => {
148+
console.error("Error fetching data: ", error);
149+
});
150+
}
151+
34152
$(document).ready(function() {
35153
36154
// Initialize Bootstrap tooltips
@@ -96,7 +214,6 @@ $(document).ready(function() {
96214
}
97215
});
98216
99-
var apiKey = "{{ request.user.api_key }}";
100217
var formName = "{{ form_name }}";
101218
102219
// console.log(formData);

libreforms_fastapi/app/templates/duplicate_form.html.jinja

+147-26
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
{% endfor %}
1717

1818
<fieldset style="padding-top: 10px;" class="form-check">
19-
<button type="submit" class="btn btn-primary" id="updateButton">Update</button>
19+
<button type="submit" class="btn btn-primary" id="createButton">Create</button>
2020
</fieldset>
2121

2222
</form>
@@ -27,10 +27,126 @@
2727
{% block scripts %}
2828
<script>
2929
30+
var apiKey = "{{ request.user.api_key }}";
31+
function getLookup(formName, fieldName, el) {
32+
33+
// Access the selected option
34+
var selectedOption = el.options[el.selectedIndex];
35+
36+
// Get the 'data-hidden' attribute from the selected option
37+
var documentData = selectedOption.getAttribute('data-hidden');
38+
var documentId = selectedOption.value;
39+
console.log(documentData);
40+
41+
const contentField = document.getElementById(`content_${fieldName}`);
42+
43+
// Clear previous contents
44+
contentField.innerHTML = '';
45+
46+
if (documentData) {
47+
let dataObj;
48+
try {
49+
dataObj = JSON.parse(documentData);
50+
} catch (error) {
51+
console.error("Parsing error:", error);
52+
return; // Stop execution if JSON is invalid.
53+
}
54+
55+
const listGroup = document.createElement("div");
56+
listGroup.className = 'list-group';
57+
58+
Object.keys(dataObj).forEach(function(key) {
59+
const listItem = document.createElement("a");
60+
listItem.className = 'list-group-item list-group-item-action';
61+
listItem.innerHTML = `<strong>${key}:</strong> ${dataObj[key]}`;
62+
listGroup.appendChild(listItem);
63+
});
64+
65+
contentField.appendChild(listGroup);
66+
67+
let oldLink = document.getElementById('lookup-link-'+fieldName);
68+
if (oldLink) {
69+
oldLink.parentNode.removeChild(oldLink);
70+
}
71+
72+
// Create an anchor element with the appropriate href
73+
let link = document.createElement('a');
74+
link.href = "/ui/form/read_one/" + formName + "/" + documentId;
75+
link.innerHTML = "Open Full Record for this Form";
76+
link.className = "btn btn-primary d-flex justify-content-center my-3";
77+
link.title = "Click here to view more details about this form.";
78+
link.target = "_blank";
79+
link.setAttribute("aria-label", "View full details for this form");
80+
link.id = 'lookup-link-'+fieldName; // Add this line to set the id
81+
82+
contentField.parentNode.insertBefore(link, contentField);
83+
84+
85+
}
86+
}
87+
88+
89+
function generateLookup(formName, fieldName, displayFields) {
90+
91+
function fetchData(formName) {
92+
return new Promise((resolve, reject) => {
93+
$.ajax({
94+
url: `/api/form/read_all/${formName}?flatten=true&exclude_journal=true&stringify_output=true&sort_by_last_edited=true&newest_first=true`,
95+
type: "GET",
96+
dataType: 'json',
97+
beforeSend: function(xhr){xhr.setRequestHeader('X-API-KEY', apiKey);},
98+
success: function(formData) {
99+
resolve(formData.documents);
100+
},
101+
error: function(xhr, status, error) {
102+
reject(error);
103+
}
104+
});
105+
});
106+
}
107+
108+
// Fetch data for the single form
109+
fetchData(formName).then(documents => {
110+
111+
// First add an empty option at the top of the list
112+
$('#' + fieldName).append($('<option>', {
113+
value: "",
114+
'data-hidden': "",
115+
text: ""
116+
}));
117+
118+
119+
var trimmedData = [];
120+
// Process documents
121+
documents.forEach(form => {
122+
// Initialize an empty string for each form
123+
let concatenatedFields = '';
124+
125+
displayFields.forEach(field => {
126+
if (form[field] !== undefined) {
127+
concatenatedFields += form[field] + ', ';
128+
}
129+
});
130+
131+
// Trim the trailing commas and spaces, and add the concatenated string to the trimmedData array
132+
concatenatedFields = concatenatedFields.replace(/,\s*$/, '');
133+
trimmedData.push(concatenatedFields);
134+
135+
// Append each concatenated string as an option to the select element
136+
$('#' + fieldName).append($('<option>', {
137+
value: form['__metadata__document_id'],
138+
'data-hidden': JSON.stringify(form),
139+
text: concatenatedFields
140+
}));
141+
});
142+
}).catch(error => {
143+
console.error("Error fetching data: ", error);
144+
});
145+
}
146+
30147
31148
$(document).ready(function() {
32149
33-
var apiKey = "{{ request.user.api_key }}";
34150
var formName = "{{ form_name }}";
35151
var documentId = "{{ document_id }}";
36152
@@ -80,27 +196,26 @@ $(document).ready(function() {
80196
// Call fetchDocumentData on page load
81197
fetchDocumentData();
82198
199+
// var elements = document.querySelectorAll('.data-lookup');
83200
84-
// Initialize Bootstrap tooltips
85-
$('[data-bs-toggle="tooltip"]').tooltip();
86-
201+
// Iterate over each element and call getLookup with appropriate parameters
202+
// elements.forEach(function(element) {
203+
// var dataLink = element.getAttribute('data-link');
204+
// var id = element.id;
205+
// getLookup(dataLink, id, element);
206+
// });
87207
88-
// Enable the Create button only if there's some data
89-
function toggleCreateButton() {
90-
var isFormFilled = $('#dataForm').find('input, textarea, select').filter(function() {
91-
return $.trim($(this).val()).length > 0;
92-
}).length > 0;
93208
94-
$createButton.prop('disabled', !isFormFilled);
95-
}
96209
97-
// Check form inputs to toggle the create button
98-
$('#dataForm').on('keyup change paste', 'input, textarea, select', toggleCreateButton);
210+
// Initialize Bootstrap tooltips
211+
$('[data-bs-toggle="tooltip"]').tooltip();
99212
100213
// Form submission event
101214
$('#dataForm').submit(function(event) {
102215
event.preventDefault(); // Prevent the form from submitting via the browser
103216
217+
// Disable the submit button
218+
$('#createButton').prop('disabled', true);
104219
105220
// Flag to track if the form is valid
106221
let formIsValid = true;
@@ -126,6 +241,9 @@ $(document).ready(function() {
126241
127242
// Prevent form submission if validation fails
128243
if (!formIsValid) {
244+
245+
// Re-enable the submit button
246+
$('#createButton').prop('disabled', false);
129247
event.preventDefault();
130248
131249
} else {
@@ -146,10 +264,16 @@ $(document).ready(function() {
146264
}
147265
});
148266
149-
// Assuming the user's API key is added in the form as a hidden field or accessible in some other way
150-
var apiKey = "{{ request.user.api_key }}";
267+
$('#dataForm').find('input:radio').each(function() {
268+
if ($(this).is(':checked')) {
269+
formData[this.name] = $(this).val();
270+
}
271+
});
272+
151273
var formName = "{{ form_name }}";
152274
275+
// console.log(formData);
276+
153277
$.ajax({
154278
url: `/api/form/create/${formName}`,
155279
type: 'POST',
@@ -161,22 +285,19 @@ $(document).ready(function() {
161285
dataType: 'json',
162286
success: function(response) {
163287
// Redirect to the read_one page with the form_name and document_id from the response
164-
setFlashMessage("Successfully updated form submission", AlertCategories.SUCCESS);
288+
setFlashMessage("Successfully created form submission", AlertCategories.SUCCESS);
165289
166-
// We purposefully delay for a second before relocating to the new document
167-
setTimeout(function() {
168-
window.location.href = `/ui/form/read_one/${formName}/${response.document_id}`;
169-
}, 1000);
290+
291+
window.location.href = `/ui/form/read_one/${formName}/${response.document_id}`;
170292
171293
},
172294
error: function(xhr) {
173-
// Handle errors, e.g., show an error message
295+
296+
// Re-enable the submit button
297+
$('#createButton').prop('disabled', false);
298+
174299
console.error('Form creation failed', xhr.responseText);
175-
// Implement flashMessage or another way to show errors to the user
176300
flashMessage(xhr.responseText, 'warning');
177-
178-
// Optionally re-enable the Create button here
179-
$createButton.prop('disabled', false);
180301
}
181302
});
182303
}

0 commit comments

Comments
 (0)