Back to index

plone3  3.1.7
validation.py
Go to the documentation of this file.
00001 from zope.component import getMultiAdapter
00002 from zope.formlib import form as formlib
00003 
00004 from kss.core import kssaction
00005 from plone.app.kss.plonekssview import PloneKSSView
00006 
00007 from Acquisition import aq_inner
00008 
00009 class FormlibValidation(PloneKSSView):
00010     """KSS actions for formlib form inline validation
00011     """
00012 
00013     @kssaction
00014     def validate_input(self, formname, fieldname, value=None):
00015         """Given a form (view) name, a field name and the submitted
00016         value, validate the given field.
00017         """
00018         
00019         # Abort if there was no value changed. Note that the actual value
00020         # comes along the submitted form, since a widget may require more than
00021         # a single form field to validate properly.
00022         if value is None:
00023             return
00024         
00025         context = aq_inner(self.context)
00026         request = aq_inner(self.request)
00027         
00028         # Find the form, the field and the widget
00029 
00030         form = getMultiAdapter((context, request), name=formname)
00031         form = form.__of__(context)
00032         
00033         raw_fieldname = fieldname[len(form.prefix)+1:]
00034         formlib_field = form.form_fields[raw_fieldname]
00035  
00036         widgets = formlib.setUpWidgets((formlib_field,), form.prefix, context, 
00037             request, form=form, adapters={}, ignore_request=False)
00038             
00039         widget = widgets[raw_fieldname]
00040         
00041         # Attempt to convert the value - this will trigge validation
00042         ksscore = self.getCommandSet('core')
00043         kssplone = self.getCommandSet('plone')
00044         validate_and_issue_message(ksscore, widget, fieldname, kssplone)
00045             
00046 def validate_and_issue_message(ksscore, widget, fieldname, kssplone=None):
00047     """A helper method also used by the inline editing view
00048     """
00049 
00050     error = None
00051     try:
00052         widget.getInputValue()
00053     except:
00054         pass
00055     error = widget.error()
00056 
00057     field_div = ksscore.getHtmlIdSelector('formfield-%s' % fieldname.replace('.', '-'))
00058     error_box = ksscore.getCssSelector('#formfield-%s div.fieldErrorBox' % fieldname.replace('.', '-'))
00059     
00060     if error:
00061         ksscore.replaceInnerHTML(error_box, error)
00062         ksscore.addClass(field_div, 'error')
00063     else:
00064         ksscore.clearChildNodes(error_box)
00065         ksscore.removeClass(field_div, 'error')
00066         if kssplone is not None: 
00067             kssplone.issuePortalMessage('')
00068 
00069     return bool(error)