feat: add button to autofill negative responses

This commit is contained in:
James Graham
2022-03-31 19:42:39 +01:00
parent 9a90b1a432
commit 3887815bbc
2 changed files with 55 additions and 1 deletions

View File

@@ -47,6 +47,7 @@ class DynamicAnswerSetBase(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.negative_responses = {}
field_order = []
for question in self.question_model.objects.all():
@@ -86,6 +87,13 @@ class DynamicAnswerSetBase(forms.Form):
self.fields[field_name] = field
field_order.append(field_name)
try:
negative_response = question.answers.get(is_negative_response=True)
self.negative_responses[field_name] = negative_response.id
except (self.answer_model.DoesNotExist, self.answer_model.MultipleObjectsReturned):
pass
if question.allow_free_text and not self.as_filters:
free_field = forms.CharField(label=f'{question} free text',
required=False)

View File

@@ -6,6 +6,13 @@
{% endif %}
{% endwith %}
<div class="alert alert-info mt-3">
If you do not know this person / organisation, you may use this button to autofill appropriate responses.
<button class="btn btn-warning" onclick="autofillNegative()">Autofill</button>
</div>
<hr>
<form class="form"
@@ -19,3 +26,42 @@
<button class="btn btn-success" type="submit">Submit</button>
{% endbuttons %}
</form>
{{ form.negative_responses|json_script:"negative-response-data" }}
<script type="application/javascript">
// Polyfill for `Object.entries` on IE
if (!Object.entries) {
Object.entries = function( obj ){
var ownProps = Object.keys( obj ),
i = ownProps.length,
resArray = new Array(i); // preallocate the Array
while (i--)
resArray[i] = [ownProps[i], obj[ownProps[i]]];
return resArray;
};
}
/**
* Autofill form with negative responses if no relationship exists.
*/
function autofillNegative() {
var data = JSON.parse(document.getElementById("negative-response-data").textContent);
var fields = Object.entries(data)
for (var i = 0, n = fields.length; i < n; i++) {
var field = fields[i]
var options = document.getElementById("id_" + field[0]).options
for (var j = 0, m = options.length; j < m; j++) {
var option = options[j]
if (option.value === field[1].toString()) {
option.selected = true
}
}
}
}
</script>
{{ form.negative_responses }}