0
0
mirror of https://github.com/wagtail/wagtail.git synced 2024-11-30 01:46:24 +01:00

Support optgroups in FilteredSelect

This commit is contained in:
Matt Westcott 2020-04-30 22:40:01 +01:00 committed by Matt Westcott
parent 15114e8918
commit ad37867bc6
2 changed files with 45 additions and 2 deletions

View File

@ -322,3 +322,37 @@ class TestFilteredSelect(TestCase):
<option value="RU" data-filter-value="AS,EU">Russia</option>
</select>
''')
def test_optgroups(self):
widget = widgets.FilteredSelect(choices=[
(None, '----'),
('Big countries', [
('FR', 'France', ['EU']),
('JP', 'Japan', ['AS']),
('RU', 'Russia', ['AS', 'EU']),
('MOON', 'The moon'),
]),
('Small countries', [
('AZ', 'Azerbaijan', ['AS']),
('LI', 'Liechtenstein', ['EU']),
]),
('SK', 'Slovakia', ['EU'])
], filter_field='id_continent')
html = widget.render('country', 'JP')
self.assertHTMLEqual(html, '''
<select name="country" data-widget="filtered-select" data-filter-field="id_continent">
<option value="">----</option>
<optgroup label="Big countries">
<option value="FR" data-filter-value="EU">France</option>
<option value="JP" selected data-filter-value="AS">Japan</option>
<option value="RU" data-filter-value="AS,EU">Russia</option>
<option value="MOON">The moon</option>
</optgroup>
<optgroup label="Small countries">
<option value="AZ" data-filter-value="AS">Azerbaijan</option>
<option value="LI" data-filter-value="EU">Liechtenstein</option>
</optgroup>
<option value="SK" data-filter-value="EU">Slovakia</option>
</select>
''')

View File

@ -53,16 +53,25 @@ class FilteredSelect(forms.Select):
subgroup = []
if isinstance(option_label, (list, tuple)):
# this is an optgroup - we will iterate over the list in the second item of
# the tuple (which has been assigned to option_label)
group_name = option_value
subindex = 0
choices = option_label
else:
# this is a top-level choice; put it in its own group with no name
group_name = None
subindex = None
choices = [(option_value, option_label)]
choices = [(option_value, option_label, filter_value)]
groups.append((group_name, subgroup, index))
for subvalue, sublabel in choices:
for choice in choices:
try:
(subvalue, sublabel, filter_value) = choice
except ValueError:
(subvalue, sublabel) = choice
filter_value = None
selected = (
str(subvalue) in value
and (not has_selected or self.allow_multiple_selected)