forms: use a template to render select widgets (#17964)

This commit is contained in:
Frédéric Péters 2017-07-25 11:16:39 +02:00
parent 3bdbe38a1b
commit ae2901f50f
2 changed files with 28 additions and 20 deletions

View File

@ -1483,6 +1483,8 @@ class CheckboxesTableWidget(TableWidget):
class SingleSelectHintWidget(SingleSelectWidget):
template_name = 'qommon/forms/widgets/select.html'
def __init__(self, name, value=None, **kwargs):
self.options_with_attributes = kwargs.pop('options_with_attributes', None)
super(SingleSelectHintWidget, self).__init__(name, value=value, **kwargs)
@ -1490,23 +1492,15 @@ class SingleSelectHintWidget(SingleSelectWidget):
def separate_hint(self):
return (self.hint and len(self.hint) > 80)
def render_content(self):
attrs = {'id': 'form_' + self.name}
if self.attrs:
attrs.update(self.attrs)
tags = [htmltag('select', name=self.name, **attrs)]
options = self.options[:]
include_disabled = False
def get_options(self):
if self.options_with_attributes:
options = self.options_with_attributes
include_disabled = True
if not self.separate_hint() and self.hint:
r = htmltag('option', value='', selected=None)
tags.append(r + htmlescape(self.hint) + htmltext('</option>'))
if self.options[0][0] is None:
# hint has been put as first element, skip the default empty
# value.
options = self.options[1:]
options = self.options_with_attributes[:]
else:
options = self.options[:]
if options[0][0] is None:
options = self.options[1:]
tags = []
for option in options:
object, description, key = option[:3]
html_attrs = {}
@ -1517,10 +1511,8 @@ class SingleSelectHintWidget(SingleSelectWidget):
html_attrs['disabled'] = 'disabled'
if description is None:
description = ''
r = htmltag('option', **html_attrs)
tags.append(r + htmlescape(description) + htmltext('</option>'))
tags.append(htmltext('</select>'))
return htmltext('\n').join(tags)
yield {'description': description, 'attrs': html_attrs,
'options': option[-1] if self.options_with_attributes else None}
def get_hint(self):
if self.separate_hint():

View File

@ -0,0 +1,16 @@
{% extends "qommon/forms/widget.html" %}
{% block widget-control %}
<select id="form_{{widget.name}}" name="{{widget.name}}"
{% for attr in widget.attrs.items %}{{attr.0}}="{{attr.1}}"{% endfor %}>
{% if not widget.separate_hint and widget.hint %}
<option value="">{{ widget.hint }}</option>
{% endif %}
{% for option in widget.get_options %}
<option{% for attr in option.attrs.items %} {{attr.0}}="{{attr.1}}"{% endfor %}>{{ option.description }}</option>
{% empty %}
{% if widget.separate_hint or not widget.hint %}
<option value="">---</option>
{% endif %}
{% endfor %}
</select>
{% endblock %}