diff --git a/src/wuttaweb/forms/schema.py b/src/wuttaweb/forms/schema.py index e4c3703..b3f0105 100644 --- a/src/wuttaweb/forms/schema.py +++ b/src/wuttaweb/forms/schema.py @@ -155,6 +155,37 @@ class WuttaEnum(colander.Enum): return widgets.SelectWidget(**kwargs) +class WuttaDictEnum(colander.String): + """ + Schema type for "pseudo-enum" fields which reference a dict for + known values instead of a true enum class. + + This is primarily for use with "status" fields such as + :attr:`~wuttjamaican:wuttjamaican.db.model.batch.BatchRowMixin.status_code`. + + This is a subclass of :class:`colander.String`, but adds a default + widget (``SelectWidget``) with enum choices. + + :param request: Current :term:`request` object. + + :param enum_dct: Dict with possible enum values and labels. + """ + + def __init__(self, request, enum_dct, *args, **kwargs): + super().__init__(*args, **kwargs) + self.request = request + self.config = self.request.wutta_config + self.app = self.config.get_app() + self.enum_dct = enum_dct + + def widget_maker(self, **kwargs): + """ """ + if 'values' not in kwargs: + kwargs['values'] = [(k, v) for k, v in self.enum_dct.items()] + + return widgets.SelectWidget(**kwargs) + + class WuttaMoney(colander.Money): """ Custom schema type for "money" fields. diff --git a/tests/forms/test_schema.py b/tests/forms/test_schema.py index 2a37aa5..3187161 100644 --- a/tests/forms/test_schema.py +++ b/tests/forms/test_schema.py @@ -81,6 +81,25 @@ class TestWuttaEnum(WebTestCase): self.assertIsInstance(widget, widgets.SelectWidget) +MOCK_STATUS_ONE = 1 +MOCK_STATUS_TWO = 2 +MOCK_STATUS = { + MOCK_STATUS_ONE: 'one', + MOCK_STATUS_TWO: 'two', +} + +class TestWuttaDictEnum(WebTestCase): + + def test_widget_maker(self): + typ = mod.WuttaDictEnum(self.request, MOCK_STATUS) + widget = typ.widget_maker() + self.assertIsInstance(widget, widgets.SelectWidget) + self.assertEqual(widget.values, [ + (1, 'one'), + (2, 'two'), + ]) + + class TestWuttaMoney(WebTestCase): def test_widget_maker(self):