Added custom boolean and list fields data converters
authorThierry Florac <tflorac@ulthar.net>
Fri, 04 Oct 2019 13:45:34 +0200
changeset 470 3219fd0a7366
parent 469 b8d287df9d34
child 471 445f6edc944d
Added custom boolean and list fields data converters
src/pyams_default_theme/shared/form/widget.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_default_theme/shared/form/widget.py	Fri Oct 04 13:45:34 2019 +0200
@@ -0,0 +1,47 @@
+#
+# Copyright (c) 2008-2019 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+from z3c.form.browser.checkbox import SingleCheckBoxWidget
+from z3c.form.interfaces import IFieldWidget
+from z3c.form.widget import FieldWidget
+from zope.schema.interfaces import IBool, IList
+
+from pyams_content.shared.form.interfaces import IFormFieldDataConverter
+from pyams_skin.layer import IPyAMSUserLayer
+from pyams_utils.adapter import adapter_config, ContextRequestAdapter
+
+
+__docformat__ = 'restructuredtext'
+
+from pyams_default_theme import _
+
+
+@adapter_config(context=(IBool, IPyAMSUserLayer), provides=IFieldWidget)
+def BooleanFieldWidget(field, request):
+    return FieldWidget(field, SingleCheckBoxWidget(request))
+
+
+@adapter_config(context=(IBool, IPyAMSUserLayer), provides=IFormFieldDataConverter)
+class BooleanFieldDataConverter(ContextRequestAdapter):
+    """Boolean field user data converter"""
+
+    def convert(self, value):
+        return self.request.localizer.translate(_("yes") if value else _("no"))
+
+
+@adapter_config(context=(IList, IPyAMSUserLayer), provides=IFormFieldDataConverter)
+class ListFieldDataConverter(ContextRequestAdapter):
+    """List field user data converter"""
+
+    @staticmethod
+    def convert(value):
+        return ', '.join(value) if value is not None else '--'