Better validation of I18n file schema fields
authorThierry Florac <thierry.florac@onf.fr>
Tue, 16 Jan 2018 17:50:57 +0100
changeset 47 3a4769b6dbcd
parent 46 e34a8c7760ea
child 48 1ad40ab71077
Better validation of I18n file schema fields
src/pyams_i18n/schema.py
--- a/src/pyams_i18n/schema.py	Mon Dec 11 15:26:52 2017 +0100
+++ b/src/pyams_i18n/schema.py	Tue Jan 16 17:50:57 2018 +0100
@@ -19,13 +19,14 @@
 from pyams_file.interfaces import DELETED_FILE
 from pyams_i18n.interfaces.schema import II18nField, II18nTextLineField, II18nTextField, II18nHTMLField, \
     II18nFileField, II18nMediaField, II18nImageField, II18nThumbnailImageField, II18nVideoField, II18nAudioField
-from z3c.form.interfaces import NOT_CHANGED
+from z3c.form.interfaces import NOT_CHANGED, IDataManager
 from zope.schema.interfaces import RequiredMissing, WrongType
 
 # import packages
 from persistent.mapping import PersistentMapping
 from pyams_file.schema import FileField, MediaField, ImageField, ThumbnailImageField, VideoField, AudioField
 from pyams_utils.schema import HTMLField
+from zope.component import getMultiAdapter
 from zope.interface import implementer
 from zope.schema import Dict, TextLine, Text
 
@@ -136,12 +137,27 @@
                 return
             if not value:
                 raise RequiredMissing
-            for lang_value in value.values():
-                if lang_value and (lang_value is not DELETED_FILE):
+            has_value = False
+            for lang, lang_value in value.items():
+                # check for NOT_CHANGED value
+                if lang_value is NOT_CHANGED:  # check for empty file value
+                    adapter = getMultiAdapter((self.context, self), IDataManager)
+                    try:
+                        old_value = adapter.query() or {}
+                    except TypeError:  # can't adapt field context => new content?
+                        old_value = None
+                    else:
+                        old_value = old_value.get(lang)
+                    has_value = has_value or bool(old_value)
+                    if has_value:
+                        break
+                elif lang_value is not DELETED_FILE:
+                    has_value = True
                     break
+            if not has_value:
                 raise RequiredMissing
         for lang_value in value.values():
-            if (lang_value is NOT_CHANGED) or (lang_value is DELETED_FILE):
+            if lang_value in (NOT_CHANGED, DELETED_FILE):
                 return
             elif isinstance(lang_value, tuple):
                 try: