Skip to content

Commit

Permalink
#88 include a hidden input field if the current option is selected to…
Browse files Browse the repository at this point in the history
… preserve it on form submit + test + release notes
  • Loading branch information
ephes committed Mar 21, 2023
1 parent 137f6f9 commit ec941fb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
22 changes: 16 additions & 6 deletions cast/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'<input type="hidden" name="{name}" value="{option_value}" />'
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 '<div class="cast-date-facet-item"><a%(attrs)s href="?%(query_string)s">%(label)s</a></div>'
return (
'<div class="cast-date-facet-item"><a%(attrs)s href="?%(query_string)s">%(label)s</a>'
"%(hidden_input)s</div>"
)


def parse_date_facets(value: str) -> datetime:
Expand Down
3 changes: 1 addition & 2 deletions docs/releases/0.2.10.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions tests/filter_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<input type="hidden" name="date_facets" value="2018-12" />' in option

0 comments on commit ec941fb

Please sign in to comment.