def write(self, fieldNode, schema, field): name = field.__name__ widget = schema.queryTaggedValue(WIDGETS_KEY, {}).get(name, None) mode = [ (i, v) for i, n, v in schema.queryTaggedValue(MODES_KEY, []) if n == name ] omitted = [ (i, v) for i, n, v in schema.queryTaggedValue(OMITTED_KEY, []) if n == name ] order = [ (d, v) for n, d, v in schema.queryTaggedValue(ORDER_KEY, []) if n == name ] if widget is not None: if not isinstance(widget, ParameterizedWidget): widget = ParameterizedWidget(widget) if widget.widget_factory or widget.params: widgetNode = etree.Element(ns('widget', self.namespace)) widgetName = widget.getWidgetFactoryName() if widgetName is not None: widgetNode.set('type', widgetName) widgetHandler = widget.getExportImportHandler(field) widgetHandler.write(widgetNode, widget.params) fieldNode.append(widgetNode) mode_values = [] for interface, value in mode: if interface is not Interface: value = "%s:%s" % (interface.__identifier__, value) mode_values.append(value) if mode_values: fieldNode.set(ns('mode', self.namespace), " ".join(mode_values)) omitted_values = [] for interface, value in omitted: if interface is not Interface: value = "%s:%s" % (interface.__identifier__, value) omitted_values.append(value) if omitted_values: fieldNode.set( ns('omitted', self.namespace), " ".join(omitted_values) ) for direction, relative_to in order: if direction == 'before': fieldNode.set(ns('before', self.namespace), relative_to) elif direction == 'after': fieldNode.set(ns('after', self.namespace), relative_to)
def updateWidgets(self): for field in self.fields.values(): if isinstance(field.field, Consent): field.widgetFactory["input"] = ParameterizedWidget(ConsentFieldWidget) elif isinstance(field.field, Divider): field.widgetFactory["input"] = ParameterizedWidget(DividerFieldWidget) elif isinstance(field.field, Choice): field.widgetFactory["input"] = ParameterizedWidget(RadioFieldWidget) elif isinstance(field.field, Set): field.widgetFactory["input"] = ParameterizedWidget(CheckBoxWidget) super(SimpleFormForm, self).updateWidgets()
def test_default_widget_instantiated(self): from plone.autoform.widgets import ParameterizedWidget from z3c.form.interfaces import IFieldWidget from zope.component import provideAdapter from zope.interface import Interface from zope.interface import implementer from zope.schema import Field class DummyWidget(object): def __init__(self, request): self.request = request @implementer(IFieldWidget) def DummyFieldWidget(field, request): return DummyWidget(request) provideAdapter(DummyFieldWidget, (Interface, Interface), IFieldWidget) field = Field() request = object() widget = ParameterizedWidget(foo='bar')(field, request) self.assertTrue(isinstance(widget, DummyWidget)) self.assertEqual('bar', widget.foo)
def read(self, fieldNode, schema, field): name = field.__name__ widgetAttr = fieldNode.get(ns('widget', self.namespace)) mode = fieldNode.get(ns('mode', self.namespace)) omitted = fieldNode.get(ns('omitted', self.namespace)) before = fieldNode.get(ns('before', self.namespace)) after = fieldNode.get(ns('after', self.namespace)) validator = fieldNode.get(ns('validator', self.namespace)) if mode: self._add_interface_values(schema, MODES_KEY, name, mode) if omitted: self._add_interface_values(schema, OMITTED_KEY, name, omitted) if before: self._add_order(schema, name, 'before', before) if after: self._add_order(schema, name, 'after', after) if validator: self._add_validator(field, validator) widgetNode = fieldNode.find(ns('widget', self.namespace)) widget = None if widgetNode is not None: # form:widget element widgetFactory = widgetNode.get('type') if widgetFactory is not None: # resolve immediately so we don't have to each time # form is rendered widgetFactory = resolveDottedName(widgetFactory) widget = ParameterizedWidget(widgetFactory) widgetHandler = widget.getExportImportHandler(field) widgetHandler.read(widgetNode, widget.params) elif widgetAttr is not None: # BBB for old form:widget attributes obj = resolveDottedName(widgetAttr) if not IFieldWidget.implementedBy(obj): raise ValueError( 'IFieldWidget not implemented by {0}'.format(obj) ) widget = widgetAttr if widget is not None: self._add(schema, WIDGETS_KEY, name, widget)
class PortletSubscribeForm(Form): fields = field.Fields(INewsletterSubscribe) ignoreContext = True fields["captcha"].widgetFactory = ReCaptchaFieldWidget fields["email"].widgetFactory = ParameterizedWidget( None, placeholder=_("Email address"), ) def __init__(self, context, request, data=None): super(PortletSubscribeForm, self).__init__(context, request) self.data = data def update(self): if not self.data.use_captcha: self.fields = self.fields.omit("captcha") super(PortletSubscribeForm, self).update() @button.buttonAndHandler(_("Subscribe"), name="subscribe") def handle_subscribe(self, action): if self.data.use_captcha: captcha = getMultiAdapter((aq_inner(self.data), self.request), name="recaptcha") if not captcha.verify(): raise WidgetActionExecutionError( "captcha", Invalid( _("Please check the captcha to prove you're a human")), ) data, errors = self.extractData() if errors: return email = data.get("email") account_id, list_id = self.data.newsletter_list.split("|") sendinblue = getUtility(ISendinblueAPI) success = sendinblue.subscribe(account_id, list_id, email) if success: api.portal.show_message( _("You are successfully subscribed to the newsletter !"), request=self.request, type="info", ) else: api.portal.show_message( _("An error occured while triyng to subscribe to the newsletter" ), request=self.request, type="error", ) url = self.request.ACTUAL_URL self.request.response.redirect(url)
def read(self, fieldNode, schema, field): name = field.__name__ widgetAttr = fieldNode.get(ns('widget', self.namespace)) mode = fieldNode.get(ns('mode', self.namespace)) omitted = fieldNode.get(ns('omitted', self.namespace)) before = fieldNode.get(ns('before', self.namespace)) after = fieldNode.get(ns('after', self.namespace)) validator = fieldNode.get(ns('validator', self.namespace)) if mode: self._add_interface_values(schema, MODES_KEY, name, mode) if omitted: self._add_interface_values(schema, OMITTED_KEY, name, omitted) if before: self._add_order(schema, name, 'before', before) if after: self._add_order(schema, name, 'after', after) if validator: self._add_validator(field, validator) widgetNode = fieldNode.find(ns('widget', self.namespace)) widget = None if widgetNode is not None: # form:widget element widgetFactory = widgetNode.get('type') if widgetFactory is not None: # resolve immediately so we don't have to each time # form is rendered widgetFactory = resolveDottedName(widgetFactory) widget = ParameterizedWidget(widgetFactory) widgetHandler = widget.getExportImportHandler(field) widgetHandler.read(widgetNode, widget.params) elif widgetAttr is not None: # BBB for old form:widget attributes obj = resolveDottedName(widgetAttr) if not IFieldWidget.implementedBy(obj): raise ValueError( 'IFieldWidget not implemented by {0}'.format(obj)) widget = widgetAttr if widget is not None: self._add(schema, WIDGETS_KEY, name, widget)
def test_validates_for_field_widget(self): from plone.autoform.widgets import ParameterizedWidget class NotAWidget(object): pass try: x = ParameterizedWidget(NotAWidget) x # PEP8 except TypeError: pass else: self.fail('Expected TypeError')
def test_write_parameterized_widget_default(self): from plone.autoform.widgets import ParameterizedWidget pw = ParameterizedWidget(None) class IDummy(Interface): dummy1 = zope.schema.Text(title=u'dummy1') IDummy.setTaggedValue(WIDGETS_KEY, {'dummy1': pw}) fieldNode = etree.Element('field') handler = FormSchema() handler.write(fieldNode, IDummy, IDummy['dummy1']) self.assertEquals(etree.tostring(fieldNode), '<field/>')
def test_write_parameterized_widget_default_with_handler(self): from plone.autoform.widgets import ParameterizedWidget pw = ParameterizedWidget(None, klass='custom') class IDummy(Interface): dummy1 = zope.schema.Text(title=u'dummy1') IDummy.setTaggedValue(WIDGETS_KEY, {'dummy1': pw}) fieldNode = etree.Element('field') handler = FormSchema() handler.write(fieldNode, IDummy, IDummy['dummy1']) self.assertEquals( etree.tostring(fieldNode), '<field><ns0:widget xmlns:ns0="http://namespaces.plone.org/supermodel/form">' '<klass>custom</klass></ns0:widget></field>')
def factory(self, field_name=None, widget_class=None, **kw): widgets = {} if field_name is None: # Usage 3 for field_name, widget in kw.items(): if not isinstance(widget, basestring): widget = "%s.%s" % (widget.__module__, widget.__name__) widgets[field_name] = widget else: if widget_class is not None \ and not IFieldWidget.implementedBy(widget_class) \ and not IWidget.implementedBy(widget_class): raise TypeError( 'widget_class must implement IWidget or IFieldWidget') widgets[field_name] = ParameterizedWidget(widget_class, **kw) return widgets
def test_write_parameterized_widget_string(self): from plone.autoform.widgets import ParameterizedWidget pw = ParameterizedWidget('foo') class IDummy(Interface): dummy1 = zope.schema.Text(title=u'dummy1') IDummy.setTaggedValue(WIDGETS_KEY, {'dummy1': pw}) fieldNode = etree.Element('field') handler = FormSchema() handler.write(fieldNode, IDummy, IDummy['dummy1']) self.assertEqual( etree.tostring(fieldNode), '<field><ns0:widget' ' xmlns:ns0="http://namespaces.plone.org/supermodel/form"' ' type="foo"/></field>')
class PortletSubscribeForm(Form): fields = field.Fields(INewsletterRedirectionSubscribe) ignoreContext = True fields["email"].widgetFactory = ParameterizedWidget( None, placeholder=_("Email address"), ) def __init__(self, context, request, data=None): super(PortletSubscribeForm, self).__init__(context, request) self.data = data @button.buttonAndHandler(_("Subscribe"), name="subscribe") def handle_subscribe(self, action): data, errors = self.extractData() if errors: return email = data.get("email") url = self.data.url self.request.response.redirect("{}{}".format(url, email))
def test_widget_instantiated_with_parameters(self): from plone.autoform.widgets import ParameterizedWidget from z3c.form.interfaces import IFieldWidget from z3c.form.interfaces import IWidget from zope.interface import implementer from zope.schema import Field @implementer(IWidget) class DummyWidget(object): def __init__(self, request): self.request = request @implementer(IFieldWidget) def DummyFieldWidget(field, request): return DummyWidget(request) field = Field() request = object() widget = ParameterizedWidget(DummyWidget, foo='bar')(field, request) self.assertTrue(isinstance(widget, DummyWidget)) self.assertEqual('bar', widget.foo)
def dexterity_update(obj, request=None): """ Utility method to update the fields of all the schemas of the Dexterity object 'obj'. """ modified = defaultdict(list) if not request: request = obj.REQUEST # Call processInputs to decode strings to unicode, otherwise the # z3c.form dataconverters complain. processInputs(request) errors = [] for schema in get_dexterity_schemas(context=obj): for name in getFieldNames(schema): # Only update fields which are included in the form # Look specifically for the empty-marker used to mark # empty checkboxes if name not in request.form and \ '%s-empty-marker' % name not in request.form: continue field = schema[name] autoform_widgets = schema.queryTaggedValue(WIDGETS_KEY, default={}) if name in autoform_widgets: widget = autoform_widgets[name] if not isinstance(widget, ParameterizedWidget): widget = ParameterizedWidget(widget) widget = widget(field, request) else: widget = component.getMultiAdapter((field, request), IFieldWidget) widget.context = obj value = field.missing_value widget.update() try: raw = widget.extract() except MultipleErrors, e: errors.append(e) log.warn("Multiple errors while extracting field: %s" % name) continue if raw is NOT_CHANGED: continue if raw is NO_VALUE: continue if (IRichTextValue.providedBy(raw) and api.portal.get_registry_record( 'ploneintranet.workspace.sanitize_html')): sanitized = RichTextValue(raw=sanitize_html( safe_unicode(raw.raw)), mimeType=raw.mimeType, outputMimeType=raw.outputMimeType) if sanitized.raw != raw.raw: log.info( 'The HTML content of field "{}" on {} was sanitised.'. format( # noqa name, obj.absolute_url())) raw = sanitized if isinstance(field, TextLine): # textLines must not contain line breaks (field contraint) # to prevent a ConstraintNotSatisfied error in `toFieldValue` raw = u" ".join(safe_unicode(raw).splitlines()) try: value = IDataConverter(widget).toFieldValue(safe_unicode(raw)) except Exception, exc: log.warn("Error in converting value for %s: %s (%s)" % (name, raw, str(exc))) raise exc try: field.validate(value) except interfaces.RequiredMissing, e: errors.append(e) log.warn("Required field have missing value: %s" % name)