Added Bytes to TextAreaWidget data converter
authorThierry Florac <thierry.florac@onf.fr>
Thu, 20 Dec 2018 14:20:36 +0100
changeset 169 e25ea6a1f7a1
parent 168 672f168d13d3
child 170 937cb818fcdc
Added Bytes to TextAreaWidget data converter
src/pyams_form/widget/__init__.py
--- a/src/pyams_form/widget/__init__.py	Tue Oct 30 12:27:16 2018 +0100
+++ b/src/pyams_form/widget/__init__.py	Thu Dec 20 14:20:36 2018 +0100
@@ -29,18 +29,18 @@
 from z3c.form.button import ButtonAction
 from z3c.form.converter import BaseDataConverter, DatetimeDataConverter as BaseDatetimeDataConverter, \
     FormatterValidationError
-from z3c.form.interfaces import DISPLAY_MODE, IButtonAction, IDataConverter, IFieldWidget, INPUT_MODE, ITextWidget, \
+from z3c.form.interfaces import DISPLAY_MODE, IButtonAction, IDataConverter, IFieldWidget, INPUT_MODE, ITextAreaWidget, \
     IWidgetLayoutTemplate, NO_VALUE
 from z3c.form.widget import FieldWidget, WidgetLayoutFactory, WidgetTemplateFactory
 from zope.component import getGlobalSiteManager
 from zope.interface import Interface, directlyProvides, implementer, implementer_only
 from zope.pagetemplate.interfaces import IPageTemplate
 from zope.schema.fieldproperty import FieldProperty
-from zope.schema.interfaces import IChoice, IDate, IDatetime, IFloat, IInt, IList, ISet, ITime, ITuple
+from zope.schema.interfaces import IBytes, IChoice, IDate, IDatetime, IFloat, IInt, IList, ISet, ITime, ITuple
 
 from pyams_form.interfaces.form import IActionWidget, ICloseWidget, IColorWidget, IDateWidget, IDatetimeWidget, \
-    IFormLayer, IHTMLWidget, IResetWidget, ISEOTextLineWidget, ISelect2Widget, ITextLineListWidget, ITimeWidget, \
-    IIntegerWidget, IFloatWidget
+    IFloatWidget, IFormLayer, IHTMLWidget, IIntegerWidget, IResetWidget, ISEOTextLineWidget, ISelect2Widget, \
+    ITextLineListWidget, ITimeWidget
 from pyams_form.schema import IActionButton, ICloseButton, IResetButton
 from pyams_skin.interfaces.tinymce import ITinyMCEConfiguration
 from pyams_utils.adapter import adapter_config
@@ -303,6 +303,23 @@
 
 
 #
+# Bytes field widget
+#
+
+@adapter_config(context=(IBytes, ITextAreaWidget), provides=IDataConverter)
+class BytesFieldDataConverter(BaseDataConverter):
+    """Bytes field data converter"""
+
+    error_message = _("Invalid UTF-8 encoded data")
+
+    def toWidgetValue(self, value):
+        return value.decode('utf-8') if isinstance(value, bytes) else value
+
+    def toFieldValue(self, value):
+        return value.encode('utf-8') if isinstance(value, str) else value
+
+
+#
 # Integer field widget
 #