From ec941fb68d2f7c278e3d21e77660a48ec269ae8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jochen=20Wersd=C3=B6rfer?= Date: Tue, 21 Mar 2023 10:59:51 +0100 Subject: [PATCH] #88 include a hidden input field if the current option is selected to preserve it on form submit + test + release notes --- cast/filters.py | 22 ++++++++++++++++------ docs/releases/0.2.10.rst | 3 +-- tests/filter_test.py | 7 +++++++ 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/cast/filters.py b/cast/filters.py index ea38618b..c0d605ee 100644 --- a/cast/filters.py +++ b/cast/filters.py @@ -68,20 +68,30 @@ def render_option(self, name: str, selected_choices: set[str], option_value: str data_dict = {k: str(v) for k, v in self.data.items() if k != "page"} data = QueryDict("", mutable=True) data.update(data_dict) - data[name] = option_value - selected = data == self.data or option_value in selected_choices + + # build the option string url = data.urlencode() - option_string = self.option_string() - return option_string % { - "attrs": selected and ' class="selected"' or "", + option_attrs, hidden_input = "", "" + if option_value in selected_choices: + # the current option is already selected, so add a hidden input field + # to preserve the selection and add the class "selected" to the link + option_attrs = ' class="selected"' + hidden_input = f'' + option_string = self.option_string() % { + "attrs": option_attrs, "query_string": url, "label": force_str(option_label), + "hidden_input": hidden_input, } + return option_string @staticmethod def option_string() -> str: - return '
%(label)s
' + return ( + '
%(label)s' + "%(hidden_input)s
" + ) def parse_date_facets(value: str) -> datetime: diff --git a/docs/releases/0.2.10.rst b/docs/releases/0.2.10.rst index 6a76eae6..28a94a4a 100644 --- a/docs/releases/0.2.10.rst +++ b/docs/releases/0.2.10.rst @@ -3,5 +3,4 @@ Filter fixes + htmx. -* #88 Fixed date facet removed after changing order -* #89 Fixed date facet removed after adding date filter +* #88 Fixed date facet is removed from form submit diff --git a/tests/filter_test.py b/tests/filter_test.py index 5a2adbd7..5eb10b2c 100644 --- a/tests/filter_test.py +++ b/tests/filter_test.py @@ -34,3 +34,10 @@ def test_active_pagination_is_removed_from_date_facet_filter(): QueryDict option = dfw.render_option("name", set(), "value", "label") assert "page=3" not in option + + +def test_selected_date_facet_is_in_hidden_input(): + dfw = DateFacetWidget() + dfw.data = QueryDict("date_facets=2018-12") + option = dfw.render_option("date_facets", {"2018-12"}, "2018-12", "2018-12 (3)") + assert '' in option