From 6faa859d7dc69ee873bda8e5e695ce4332462435 Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Mon, 16 Sep 2019 19:03:52 +0200 Subject: Forms: manage conditionnal field inside a same form with JS --- ishtar_common/forms.py | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) (limited to 'ishtar_common/forms.py') diff --git a/ishtar_common/forms.py b/ishtar_common/forms.py index 24972ed3b..c9c88b805 100644 --- a/ishtar_common/forms.py +++ b/ishtar_common/forms.py @@ -617,6 +617,7 @@ class FormHeader(object): class IshtarForm(forms.Form, BSForm): TYPES = [] # FieldType list + CONDITIONAL_FIELDS = [] # dynamic conditions on field display PROFILE_FILTER = {} # profile key associated to field list HEADERS = {} # field key associated to FormHeader instance SITE_KEYS = {} # archaeological sites fields and associated translation key @@ -659,6 +660,72 @@ class IshtarForm(forms.Form, BSForm): self.current_header = self.HEADERS[key] return self.current_header + def extra_render(self): + return self.get_conditional() + + HIDE_JS_TEMPLATE = """ + var %(id)s_item_show_list = ['%(item_list)s']; + for (idx in %(id)s_item_show_list){ + $("#main_div-id_" + %(id)s_item_show_list[idx]).addClass("d-none"); + } + """ + CONDITIONAL_JS_TEMPLATE = """ + var %(id)s_check_list = ['%(check_id_list)s']; + var %(id)s_item_show_list = ['%(item_list)s']; + var %(id)s_hide_display = function(){ + var current_val = $("#id_%(name)s").val(); + console.log("#id_%(name)s"); + if (%(id)s_check_list.indexOf(current_val) != -1){ + for (idx in %(id)s_item_show_list){ + $("#main_div-id_" + %(id)s_item_show_list[idx]).removeClass("d-none"); + } + } else { + for (idx in %(id)s_item_show_list){ + $("#main_div-id_" + %(id)s_item_show_list[idx]).addClass("d-none"); + } + } + }; + + $("#id_%(name)s").change(%(id)s_hide_display); + setTimeout(function(){ + %(id)s_hide_display(); + }, 500); + """ + + def get_conditional(self): + if not self.CONDITIONAL_FIELDS or not self.TYPES: + return + + type_dict = dict([(typ.key, typ.model) for typ in self.TYPES]) + html = "" + for condition, target_names in self.CONDITIONAL_FIELDS: + condition_field, condition_attr, condition_val = condition + if condition_field not in type_dict: + continue + model = type_dict[condition_field] + condition_ids = [ + str(item.pk) for item in model.objects.filter( + **{condition_attr: condition_val}).all() + ] + name = self.prefix + "-" + condition_field + target_names = [ + self.prefix + "-" + name for name in target_names + ] + if not condition_ids: + html += self.HIDE_JS_TEMPLATE % { + "item_list": "','".join(target_names), + "id": name.replace("-", "_")} + continue + html += self.CONDITIONAL_JS_TEMPLATE % { + "id": name.replace("-", "_"), + "name": name, + "item_list": "','".join(target_names), + "check_id_list": "','".join(condition_ids), + } + if html: + html = "" + return html + class TableSelect(IshtarForm): def __init__(self, *args, **kwargs): -- cgit v1.2.3