[widgets] an option for Select to show sorted content tls-sprint
authorAurelien Campeas <aurelien.campeas@logilab.fr>
Wed, 29 Apr 2009 12:51:43 +0200
branchtls-sprint
changeset 1541 ddddbb748355
parent 1540 996355824825
child 1544 d8fb60c56d69
child 1559 c4d4851bd18b
[widgets] an option for Select to show sorted content
web/formwidgets.py
--- a/web/formwidgets.py	Wed Apr 29 12:13:47 2009 +0200
+++ b/web/formwidgets.py	Wed Apr 29 12:51:43 2009 +0200
@@ -159,16 +159,20 @@
 
 class Select(FieldWidget):
     """<select>, for field having a specific vocabulary"""
-    def __init__(self, attrs=None, multiple=False):
+    def __init__(self, attrs=None, multiple=False, sort=False):
         super(Select, self).__init__(attrs)
-        self.multiple = multiple
+        self._multiple = multiple
+        self._sort = sort
 
     def render(self, form, field):
         name, curvalues, attrs = self._render_attrs(form, field)
-        if not 'size' in attrs and self.multiple:
+        if not 'size' in attrs and self._multiple:
             attrs['size'] = '5'
         options = []
-        for label, value in field.vocabulary(form):
+        vocab = field.vocabulary(form)
+        if self._sort:
+            vocab = sorted(vocab)
+        for label, value in vocab:
             if value is None:
                 # handle separator
                 options.append(u'<optgroup label="%s"/>' % (label or ''))
@@ -176,7 +180,7 @@
                 options.append(tags.option(label, value=value, selected='selected'))
             else:
                 options.append(tags.option(label, value=value))
-        return tags.select(name=name, multiple=self.multiple,
+        return tags.select(name=name, multiple=self._multiple,
                            options=options, **attrs)