예제 #1
0
    def widget(self, _context, field, **kw):
        attrs = kw
        class_ = attrs.pop("class_", None)
        # Try to do better than accepting the string value by looking through
        # the interfaces and trying to find the field, so that we can use
        # 'fromUnicode()'
        if isinstance(class_, type):
            ifaces = implementedBy(class_)
            for name, value in kw.items():
                for iface in ifaces:
                    if name in iface:
                        attrs[name] = iface[name].fromUnicode(value)
                        break
        if class_ is None:
            # The _default_widget_factory is required to allow the
            # <widget> directive to be given without a "class"
            # attribute.  This can be used to override some of the
            # presentational attributes of the widget implementation.
            class_ = self._default_widget_factory
        
        # don't wrap a factory into a factory
        if IViewFactory.providedBy(class_):
            factory = class_
        else:
            factory = CustomWidgetFactory(class_, **attrs)

        self._widgets[field+'_widget'] = factory
예제 #2
0
def setUpWidget(view, name, field, viewType, value=no_value, prefix=None,
                ignoreStickyValues=False, context=None):
    """Sets up a single view widget.

    The widget will be an attribute of the `view`. If there is already
    an attribute of the given name, it must be a widget and it will be
    initialized with the given `value` if not ``no_value``.

    If there isn't already a `view` attribute of the given name, then a
    widget will be created and assigned to the attribute.
    """
    if context is None:
        context = view.context
    widgetName = name + '_widget'
    
    # check if widget already exists
    widget = getattr(view, widgetName, None)
    if widget is None:
        # does not exist - create it
        widget = _createWidget(context, field, viewType, view.request)
        setattr(view, widgetName, widget)
    elif IViewFactory.providedBy(widget):
        # exists, but is actually a factory - use it to create the widget
        widget = widget(field.bind(context), view.request)
        setattr(view, widgetName, widget)
        
    # widget must implement IWidget
    if not IWidget.providedBy(widget):
        raise TypeError(
            "Unable to configure a widget for %s - attribute %s does not "
            "implement IWidget" % (name, widgetName))
    
    if prefix:
        widget.setPrefix(prefix)
        
    if value is not no_value and (
        ignoreStickyValues or not _widgetHasStickyValue(widget)):
        widget.setRenderedValue(value)