Added "add_error" method to base form
authorThierry Florac <tflorac@ulthar.net>
Fri, 26 Jul 2019 18:36:18 +0200
changeset 181 f0e082a0cb75
parent 180 2f4027a2d6c8
child 182 349100f57541
Added "add_error" method to base form
src/pyams_form/form.py
src/pyams_form/interfaces/form.py
--- a/src/pyams_form/form.py	Fri Jul 26 12:34:54 2019 +0200
+++ b/src/pyams_form/form.py	Fri Jul 26 18:36:18 2019 +0200
@@ -29,7 +29,7 @@
     applyChanges
 from z3c.form.interfaces import DISPLAY_MODE, IErrorViewSnippet, IMultipleErrors
 from zope.component import queryUtility
-from zope.interface import Interface, alsoProvides, classImplements, implementer
+from zope.interface import Interface, alsoProvides, classImplements, implementer, Invalid
 from zope.lifecycleevent import Attributes, ObjectCreatedEvent
 from zope.location import locate
 from zope.publisher.interfaces.browser import IBrowserRequest
@@ -196,6 +196,19 @@
             result.extend(form.widgets.errors)
         return result
 
+    def add_error(self, error, widget):
+        if isinstance(error, str):
+            error = Invalid(error)
+        if isinstance(widget, str):
+            widget = self.widgets[widget]
+        snippet = self.request.registry.getMultiAdapter((error, self.request, widget,
+                                                         widget.field, self, self.context),
+                                                        IErrorViewSnippet)
+        snippet.update()
+        widget.error = snippet
+        self.widgets.errors += (snippet,)
+        self.status = error.args[0]
+
     def update_content(self, content, data):
         changes = applyChanges(self, content, data.get(self, data))
         for subform in self.get_forms(include_self=False):
--- a/src/pyams_form/interfaces/form.py	Fri Jul 26 12:34:54 2019 +0200
+++ b/src/pyams_form/interfaces/form.py	Fri Jul 26 18:36:18 2019 +0200
@@ -133,6 +133,13 @@
 
     is_dialog = Attribute("Check to know if current form is in a modal dialog")
 
+    def add_error(self, error, widget):
+        """Add error to current form status
+
+        :param error: error can be defined as a simple string or as an error instance.
+        :param widget: widget can be a widget name or a Widget instance.
+        """
+
     def get_form_action(self):
         """Get form action URL"""