Move invariant verification error message to field in Plone

I use Plone with dexterity, and I check 2 related fields using an invariant decorator. Everything works, but ... I would like to move the general error message to one specific field.

How can i do this? I found Martin Aspelie's three-year suggestion about how cool it would be to do this:

http://plone.293351.n2.nabble.com/plone-app-form-does-not-display-invariant-errors-td348710.html

but they did not come out with a decision.

I also found a way to do this, but it's ugly: putting this code on the form refresh method:

for widget in widgets: name = widget.context.getName() if errors: for error in errors: if isinstance(error, Invalid) and name in error.args[1:]: if widget._error is None: widget._error = error 

Is there a lower-level implementation that allows you to pass field names to the raised Invalid and does not require a loop through all fields and all errors for each field?!?

+4
source share
1 answer

You can do this by doing an additional check in the form handler and raise a WidgetActionExecutionError, specifying the widget for which the error should be displayed.

It looks like this (taken from http://plone.org/products/dexterity/documentation/manual/schema-driven-forms/customising-form-behaviour/validation ):

 from five import grok from plone.directives import form from zope.interface import invariant, Invalid from zope import schema from z3c.form import button from z3c.form.interfaces import ActionExecutionError, WidgetActionExecutionError from Products.CMFCore.interfaces import ISiteRoot from Products.statusmessages.interfaces import IStatusMessage from example.dexterityforms.interfaces import MessageFactory as _ ... class OrderForm(form.SchemaForm): ... @button.buttonAndHandler(_(u'Order')) def handleApply(self, action): data, errors = self.extractData() # Some additional validation if 'address1' in data and 'address2' in data: if len(data['address1']) < 2 and len(data['address2']) < 2: raise ActionExecutionError(Invalid(_(u"Please provide a valid address"))) elif len(data['address1']) < 2 and len(data['address2']) > 10: raise WidgetActionExecutionError('address2', Invalid(u"Please put the main part of the address in the first field")) if errors: self.status = self.formErrorsMessage return 

I think it is also possible to raise a WidgetActionExecutionError from your invariant, but then it may not do what you want if the invariant receives validation at a different time than when processing the z3c.form form.

+2
source

Source: https://habr.com/ru/post/1436549/


All Articles