From 1cc2c2f30ce07d3abfc0507ac389caa553806e18 Mon Sep 17 00:00:00 2001 From: "Mees, T.D. (Ty)" Date: Thu, 7 Dec 2023 12:51:49 +0100 Subject: [PATCH] feat: added select2 widget --- dev/main/forms.py | 14 ++++++++++++++ src/cdh/core/forms.py | 18 ++++++++++++++++++ .../cdh.core/js/widget/searchable-select.js | 3 +++ 3 files changed, 35 insertions(+) create mode 100644 src/cdh/core/static/cdh.core/js/widget/searchable-select.js diff --git a/dev/main/forms.py b/dev/main/forms.py index 77a47daf..3116f399 100644 --- a/dev/main/forms.py +++ b/dev/main/forms.py @@ -82,6 +82,20 @@ class FormStylesForm(forms.Form): widget=forms.RadioSelect, ) + searchable_select = forms.ChoiceField( + choices=[ + (1, "Train"), + (2, "Bus"), + (3, "Aeroplane"), + (4, "Bike"), + (5, "Feet"), + (6, "Magical Unicorn"), + (6, "Broom"), + (6, "Thestrals"), + ], + widget=core_fields.SearchableSelectWidget, + ) + integer = forms.IntegerField() float = forms.FloatField(help_text="Floating away") diff --git a/src/cdh/core/forms.py b/src/cdh/core/forms.py index 0f5b7edd..5d8fc497 100644 --- a/src/cdh/core/forms.py +++ b/src/cdh/core/forms.py @@ -99,6 +99,24 @@ def get_context(self, name, value, attrs): return super().get_context(name, value, attrs) +class SearchableSelectWidget(BootstrapSelect): + """A JS-baced widget for a searchable select. Currently using Select2 as + the backend.""" + + class Media: + js = [ + 'cdh.core/js/widget/searchable-select.js', + ] + + def get_context(self, name, value, attrs): + if "class" not in attrs: + attrs["class"] = "" + + attrs["class"] += " dsc-select2" + + return super().get_context(name, value, attrs) + + class BootstrapCheckboxInput(CheckboxInput): """Override of Django's version to use the right Bootstrap classes""" diff --git a/src/cdh/core/static/cdh.core/js/widget/searchable-select.js b/src/cdh/core/static/cdh.core/js/widget/searchable-select.js new file mode 100644 index 00000000..e22d7caa --- /dev/null +++ b/src/cdh/core/static/cdh.core/js/widget/searchable-select.js @@ -0,0 +1,3 @@ +$(() => { + $('.dsc-select2').select2(); +}) \ No newline at end of file