Skip to main content

The Original Zope 3 Form Framework

Project description

This package provides a form and widget framework for Zope 3. It also implements a few high-level ZCML directives for declaring forms. More advanced alternatives are implemented in zope.formlib and z3c.form.

Detailed documentation:

Browser Widgets

This directory contains widgets: views on bound schema fields. Many of these are straightforward. For instance, see the TextWidget in textwidgets.py, which is a subclass of BrowserWidget in widget.py. It is registered as an IBrowserRequest view of an ITextLine schema field, providing the IInputWidget interface:

<view
    type="zope.publisher.interfaces.browser.IBrowserRequest"
    for="zope.schema.interfaces.ITextLine"
    provides="zope.app.form.interfaces.IInputWidget"
    factory=".TextWidget"
    permission="zope.Public"
    />

The widget then receives the field and the request as arguments to the factory (i.e., the TextWidget class).

Some widgets in Zope 3 extend this pattern. This extension is configurable: simply do not load the zope/app/form/browser/configure.zcml file if you do not wish to participate in the extension. The widget registration is extended for Choice fields and for the collection fields.

Default Choice Field Widget Registration and Lookup

As described above, all field widgets are obtained by looking up a browser IInputWidget or IDisplayWidget view for the field object. For Choice fields, the default registered widget defers all of its behavior to the result of another lookup: a browser widget view for the field and the Choice field’s vocabulary.

This allows registration of Choice widgets that differ on the basis of the vocabulary type. For example, a widget for a vocabulary of images might have a significantly different user interface than a widget for a vocabulary of words. A dynamic vocabulary might implement IIterableVocabulary if its contents are below a certain length, but not implement the marker “iterable” interface if the number of possible values is above the threshhold.

This also means that choice widget factories are called with with an additional argument. Rather than being called with the field and the request as arguments, choice widgets receive the field, vocabulary, and request as arguments.

Some Choice widgets may also need to provide a query interface, particularly if the vocabulary is too big to iterate over. The vocabulary may provide a query which implements an interface appropriate for that vocabulary. You then can register a query view – a view registered for the query interface and the field interface – that implements zope.app.forms.browser.interfaces.IVocabularyQueryView.

Default Collection Field Widget Registration and Lookup

The default configured lookup for collection fields – List, Tuple, and Set, for instance – begins with the usual lookup for a browser widget view for the field object. This widget defers its display to the result of another lookup: a browser widget view registered for the field and the field’s value_type (the type of the contained values). This allows registrations for collection widgets that differ on the basis of the members – a widget for entering a list of text strings might differ significantly from a widget for entering a list of dates…or even a list of choices, as discussed below.

This registration pattern has three implications that should be highlighted.

  • First, collection fields that do not specify a value_type probably cannot have a reasonable widget.

  • Second, collection widgets that wish to be the default widget for a collection with any value_type should be registered for the collection field and a generic value_type: the IField interface. Do not register the generic widget for the collection field only or you will break the lookup behavior as described here.

  • Third, like choice widget factories, sequence widget factories (classes or functions) take three arguments. Typical sequence widgets receive the field, the value_type, and the request as arguments.

Collections of Choices

If a collection field’s value_type is a Choice field, the second widget again defers its behavior, this time to a third lookup based on the collection field and the choice’s vocabulary. This means that a widget for a list of large image choices can be different than a widget for a list of small image choices (with a different vocabulary interface), different from a widget for a list of keyword choices, and different from a set of keyword choices.

Some advanced applications may wish to do a further lookup on the basis of the unique attribute of the collection field–perhaps looking up a named view with a “unique” or “lenient” token depending on the field’s value, but this is not enabled in the default Zope 3 configuration.

Registering Widgets for a New Collection Field Type

Because of this lookup pattern, basic widget registrations for new field types must follow a recipe. For example, a developer may introduce a new Bag field type for simple shopping cart functionality and wishes to add widgets for it within the default Zope 3 collection widget registration. The bag widgets should be registered something like this.

The only hard requirement is that the developer must register the bag + choice widget: the widget is just the factory for the third dispatch as described above, so the developer can use the already implemented widgets listed below:

<view
    type="zope.publisher.interfaces.browser.IBrowserRequest"
    for="zope.schema.interfaces.IBag
         zope.schema.interfaces.IChoice"
    provides="zope.app.form.interfaces.IDisplayWidget"
    factory=".ChoiceCollectionDisplayWidget"
    permission="zope.Public"
    />

<view
    type="zope.publisher.interfaces.browser.IBrowserRequest"
    for="zope.schema.interfaces.IBag
         zope.schema.interfaces.IChoice"
    provides="zope.app.form.interfaces.IInputWidget"
    factory=".ChoiceCollectionInputWidget"
    permission="zope.Public"
    />

Beyond this, the developer may also have a generic bag widget she wishes to register. This might look something like this, assuming there’s a BagSequenceWidget available in this package:

<view
    type="zope.publisher.interfaces.browser.IBrowserRequest"
    for="zope.schema.interfaces.IBag
         zope.schema.interfaces.IField"
    provides="zope.app.form.interfaces.IInputWidget"
    factory=".BagSequenceWidget"
    permission="zope.Public"
    />

Then any widgets for the bag and a vocabulary would be registered according to this general pattern, in which IIterableVocabulary would be the interface of any appropriate vocabulary and BagWidget is some appropriate widget:

<view
    type="zope.publisher.interfaces.browser.IBrowserRequest"
    for="zope.schema.interfaces.IBag
         zope.schema.interfaces.IIterableVocabulary"
    provides="zope.app.form.interfaces.IInputWidget"
    factory=".BagWidget"
    permission="zope.Public"
    />

Choice widgets and the missing value

Choice widgets for a non-required field include a “no value” item to allow for not selecting any value at all. This value used to be omitted for required fields on the assumption that the widget should avoid invalid input from the start.

However, if the context object doesn’t yet have a field value set and there’s no default value, a dropdown widget would have to select an arbitrary value due to the way it is displayed in the browser. This way, the field would always validate, but possibly with a value the user never chose consciously.

Starting with version 3.6.0, dropdown widgets for required fields display a “no value” item even for required fields if an arbitrary value would have to be selected by the widget otherwise.

To switch the old behaviour back on for backwards compatibility, do

zope.app.form.browser.itemswidgets.EXPLICIT_EMPTY_SELECTION = False

during application start-up.

Simple example showing ObjectWidget and SequenceWidget usage

The following implements a Poll product (add it as zope/app/demo/poll) which has poll options defined as:

label

A TextLine holding the label of the option

description

Another TextLine holding the description of the option

Simple stuff.

Our Poll product holds an editable list of the PollOption instances. This is shown in the poll.py source below:

from persistent import Persistent
from interfaces import IPoll, IPollOption
from zope.interface import implements, classImplements

class PollOption(Persistent, object):
    implements(IPollOption)

class Poll(Persistent, object):
    implements(IPoll)

    def getResponse(self, option):
        return self._responses[option]

    def choose(self, option):
        self._responses[option] += 1
        self._p_changed = 1

    def get_options(self):
        return self._options

    def set_options(self, options):
        self._options = options
        self._responses = {}
        for option in self._options:
            self._responses[option.label] = 0

    options = property(get_options, set_options, None, 'fiddle options')

And the Schemas are defined in the interfaces.py file below:

from zope.interface import Interface
from zope.schema import Object, Tuple, TextLine
from zope.schema.interfaces import ITextLine
from zope.i18nmessageid import MessageFactory

_ = MessageFactory("poll")

class IPollOption(Interface):
    label = TextLine(title=u'Label', min_length=1)
    description = TextLine(title=u'Description', min_length=1)

class IPoll(Interface):
    options = Tuple(title=u'Options',
        value_type=Object(IPollOption, title=u'Poll Option'))

    def getResponse(option): "get the response for an option"

    def choose(option): 'user chooses an option'

Note the use of the Tuple and Object schema fields above. The Tuple could optionally have restrictions on the min or max number of items - these will be enforced by the SequenceWidget form handling code. The Object must specify the schema that is used to generate its data.

Now we have to specify the actual add and edit views. We use the existing AddView and EditView, but we pre-define the widget for the sequence because we need to pass in additional information. This is given in the browser.py file:

from zope.app.form.browser.editview import EditView
from zope.app.form.browser.add import AddView
from zope.app.form import CustomWidgetFactory
from zope.app.form.browser import SequenceWidget, ObjectWidget

from interfaces import IPoll
from poll import Poll, PollOption

class PollVoteView:
    __used_for__ = IPoll

    def choose(self, option):
        self.context.choose(option)
        self.request.response.redirect('.')

ow = CustomWidgetFactory(ObjectWidget, PollOption)
sw = CustomWidgetFactory(SequenceWidget, subwidget=ow)

class PollEditView(EditView):
    __used_for__ = IPoll

    options_widget = sw

class PollAddView(AddView):
    __used_for__ = IPoll

    options_widget = sw

Note the creation of the widget via a CustomWidgetFactory. So, whenever the options_widget is used, a new SequenceWidget(subwidget=CustomWidgetFactory(ObjectWidget, PollOption)) is created. The subwidget argument indicates that each item in the sequence should be represented by the indicated widget instead of their default. If the contents of the sequence were just Text fields, then the default would be just fine - the only odd cases are Sequence and Object Widgets because they need additional arguments when they’re created.

Each item in the sequence will be represented by a CustomWidgetFactory(ObjectWidget, PollOption) - thus a new ObjectWidget(context, request, PollOption) is created for each one. The PollOption class (“factory”) is used to create new instances when new data is created in add forms (or edit forms when we’re adding new items to a Sequence).

Tying all this together is the configure.zcml:

<configure xmlns='http://namespaces.zope.org/zope'
    xmlns:browser='http://namespaces.zope.org/browser'>

<content class=".poll.Poll">
<factory id="zope.app.demo.poll"
         permission="zope.ManageContent" />

<implements
    interface="zope.annotation.interfaces.IAttributeAnnotatable"
    />

<require
    permission="zope.View"
    interface=".interfaces.IPoll"
    />

<require
    permission="zope.ManageContent"
    set_schema=".interfaces.IPoll"
    />
</content>

<content class=".poll.PollOption">
<require
    permission="zope.View"
    interface=".interfaces.IPollOption"
    />
</content>

<browser:page for=".interfaces.IPoll"
    name="index.html"
    template="results.zpt"
    permission="zope.View"
    menu="zmi_views" title="View"
    />

<browser:pages
    for=".interfaces.IPoll"
    class=".browser.PollVoteView"
    permission="zope.ManageContent">
    <browser:page name="vote.html" template="vote.zpt"
        menu="zmi_views" title="Vote" />
    <browser:page name="choose" attribute="choose" />
</browser:pages>

<browser:addform
    schema=".interfaces.IPoll"
    label="Add a Poll"
    content_factory=".poll.Poll"
    name="AddPoll.html"
    class=".browser.PollAddView"
    permission="zope.ManageContent" />

<browser:addMenuItem
    title="Poll Demo"
    description="Poll Demo"
    content_factory=".poll.Poll"
    view="AddPoll.html"
    permission="zope.ManageContent"
    />


<browser:editform
    schema=".interfaces.IPoll"
    class=".browser.PollEditView"
    label="Change a Poll"
    name="edit.html"
    menu="zmi_views" title="Edit"
    permission="zope.ManageContent" />

</configure>

Note the use of the class attribute on the addform and editform elements. Otherwise, nothing much exciting here.

Finally, we have some additional views…

results.zpt:

<html metal:use-macro="context/@@standard_macros/page">
<title metal:fill-slot="title">Poll results</title>
<div metal:fill-slot="body">
<table border="1">
<caption>Poll results</caption>
<thead>
    <tr><th>Option</th><th>Results</th><th>Description</th></tr>
</thead>
<tbody>
    <tr tal:repeat="option context/options">
    <td tal:content="option/label">Option</td>
    <td tal:content="python:context.getResponse(option.label)">Result</td>
    <td tal:content="option/description">Option</td>
    </tr>
</tbody>
</table>
</div>
</html>

vote.zpt:

<html metal:use-macro="context/@@standard_macros/page">
<title metal:fill-slot="title">Poll voting</title>
<div metal:fill-slot="body">
<form action="choose">
<table border="1">
<caption>Poll voting</caption>
<tbody>
    <tr tal:repeat="option context/options">
    <td><input type="radio" name="option"
                tal:attributes="value option/label"></td>
    <td tal:content="option/label">Option</td>
    <td tal:content="option/description">Option</td>
    </tr>
</tbody>
</table>
<input type="submit">
</form>
</div>
</html>

Object Widget

The following example shows a Family with Mother and Father. First define the interface for a person:

>>> from zope.interface import Interface, implements
>>> from zope.schema import TextLine
>>> class IPerson(Interface):
...     """Interface for Persons."""
...
...     name = TextLine(title=u'Name', description=u'The first name')

Let’s define the class:

>>> class Person(object):
...
...     implements(IPerson)
...
...     def __init__(self, name=''):
...         self.name = name

Let’s define the interface family:

>>> from zope.schema import Object
>>> class IFamily(Interface):
...     """The familiy interface."""
...
...     mother = Object(title=u'Mother',
...                     required=False,
...                     schema=IPerson)
...
...     father = Object(title=u'Father',
...                     required=False,
...                     schema=IPerson)

Let’s define the class family with FieldProperty’s mother and father FieldProperty validate the values if they get added:

>>> from zope.schema.fieldproperty import FieldProperty
>>> class Family(object):
...     """The familiy interface."""
...
...     implements(IFamily)
...
...     mother = FieldProperty(IFamily['mother'])
...     father = FieldProperty(IFamily['father'])
...
...     def __init__(self, mother=None, father=None):
...         self.mother = mother
...         self.father = father

Let’s make a instance of Family with None attributes:

>>> family = Family()
>>> bool(family.mother == None)
True
>>> bool(family.father == None)
True

Let’s make a instance of Family with None attributes:

>>> mother = Person(u'Margrith')
>>> father = Person(u'Joe')
>>> family = Family(mother, father)
>>> IPerson.providedBy(family.mother)
True
>>> IPerson.providedBy(family.father)
True

Let’s define a dummy class which doesn’t implements IPerson:

>>> class Dummy(object):
...     """Dummy class."""
...     def __init__(self, name=''):
...         self.name = name

Raise a SchemaNotProvided exception if we add a Dummy instance to a Family object:

>>> foo = Dummy('foo')
>>> bar = Dummy('bar')
>>> family = Family(foo, bar)
Traceback (most recent call last):
...
SchemaNotProvided

Now let’s setup a enviroment for use the widget like in a real application:

>>> from zope.app.testing import ztapi
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema.interfaces import ITextLine
>>> from zope.schema import TextLine
>>> from zope.app.form.browser import TextWidget
>>> from zope.app.form.browser import ObjectWidget
>>> from zope.app.form.interfaces import IInputWidget

Register the TextLine widget used in the IPerson interface for the field ‘name’.

>>> ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)

Let’s define a request and provide input value for the mothers name used in the family object:

>>> request = TestRequest(HTTP_ACCEPT_LANGUAGE='pl')
>>> request.form['field.mother.name'] = u'Margrith Ineichen'

Before we update the object let’s check the value name of the mother instance on the family object:

>>> family.mother.name
u'Margrith'

Now let’s initialize a ObjectWidget with the right attributes:

>>> mother_field = IFamily['mother']
>>> factory = Person
>>> widget = ObjectWidget(mother_field, request, factory)

Now comes the magic. Apply changes means we force the ObjectWidget to read the request, extract the value and save it on the content. The ObjectWidget instance uses a real Person class (factory) for add the value. The value is temporary stored in this factory class. The ObjectWidget reads the value from this factory and set it to the attribute ‘name’ of the instance mother (The object mother is allready there). If we don’t have a instance mother allready store in the family object, the factory instance will be stored directly to the family attribute mother. For more information see the method ‘applyChanges()’ in the interface zope.app.form.browser.objectwidget.ObjectWidget.

>>> widget.applyChanges(family)
True

Test the updated mother’s name value on the object family:

>>> family.mother.name
u'Margrith Ineichen'
>>> IPerson.providedBy(family.mother)
True

So, now you know my mothers and fathers name. I hope it’s also clear how to use the Object field and the ObjectWidget.

Source Widgets

Sources are objects that represent sets of values from which one might choose and are used with Choice schema fields. Source widgets currently fall into two categories:

  • widgets for iterable sources

  • widgets for queryable sources

Sources (combined with the available adapters) may support both approaches, but no widgets currently support both.

In both cases, the widgets need views that can be used to get tokens to represent source values in forms, as well as textual representations of values. We use the zope.browser.interfaces.ITerms views for that.

All of our examples will be using the component architecture:

>>> import zope.interface
>>> import zope.component
>>> import zope.schema

This ITerms implementation can be used for the sources involved in our tests:

>>> from zope.browser.interfaces import ITerms
>>> import zope.publisher.interfaces.browser
>>> import zope.app.form.browser.interfaces
>>> from zope.schema.vocabulary import SimpleTerm
>>> class ListTerms:
...
...     zope.interface.implements(ITerms)
...
...     def __init__(self, source, request):
...         pass # We don't actually need the source or the request :)
...
...     def getTerm(self, value):
...         title = unicode(value)
...         try:
...             token = title.encode('base64').strip()
...         except binascii.Error:
...             raise LookupError(token)
...         return SimpleTerm(value, token=token, title=title)
...
...     def getValue(self, token):
...         return token.decode('base64')

This view just uses the unicode representations of values as titles and the base-64 encoding of the titles as tokens. This is a very simple strategy that’s only approriate when the values have short and unique unicode representations.

All of the source widgets are in a single module:

>>> import zope.app.form.browser.source

We’ll also need request objects:

>>> from zope.publisher.browser import TestRequest

Iterable Source Widgets

Iterable sources are expected to be simpler than queriable sources, so they represent a good place to start. The most important aspect of iterable sources for widgets is that it’s actually possible to enumerate all the values from the source. This allows each possible value to be listed in a <select> form field.

Let’s start with a simple example. We have a very trivial source, which is basically a list:

>>> class SourceList(list):
...     zope.interface.implements(zope.schema.interfaces.IIterableSource)

We need to register our ITerms view:

>>> zope.component.provideAdapter(
...     ListTerms,
...     (SourceList, zope.publisher.interfaces.browser.IBrowserRequest))

Let’s define a choice field using our iterable source:

>>> dog = zope.schema.Choice(
...    __name__ = 'dog',
...    title=u"Dogs",
...    source=SourceList(['spot', 'bowser', 'prince', 'duchess', 'lassie']),
...    )

>>> dog = dog.bind(object())

When we get a choice input widget for a choice field, the default widget factory gets a view on the field and the field’s source. We’ll just create the view directly:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceSelectWidget(
...     dog, dog.source, request)

>>> print widget()
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>

Since the field is required, an empty selection is not valid:

>>> widget.getInputValue()
Traceback (most recent call last):
MissingInputError: ('field.dog', u'Dogs', None)

Also, the widget is required in this case:

>>> widget.required
True

If the request contains a value, it is marked as selected:

>>> request.form["field.dog-empty-marker"] = "1"
>>> request.form["field.dog"] = "Ym93c2Vy"

>>> print widget()
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option selected="selected" value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>

If we set the displayed value for the widget, that value is marked as selected:

>>> widget.setRenderedValue("duchess")
>>> print widget()
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option selected="selected" value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>

Dropdown widgets are achieved with SourceDropdownWidget, which simply generates a selection list of size 1:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceDropdownWidget(
...     dog, dog.source, request)
>>> print widget() # doctest: +ELLIPSIS
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="1" >
<option selected="selected" value="">(no value)</option>...

An alternative to SourceSelectWidget for small numbers of items is SourceRadioWidget that provides a radio button group for the items:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceRadioWidget(
...     dog, dog.source, request)
>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dog.0"><input class="radioType" id="field.dog.0"
    name="field.dog" type="radio" value="c3BvdA==" />&nbsp;spot</label><br
/><label for="field.dog.1"><input class="radioType" id="field.dog.1"
    name="field.dog" type="radio" value="Ym93c2Vy" />&nbsp;bowser</label><br
/><label for="field.dog.2"><input class="radioType" id="field.dog.2"
    name="field.dog" type="radio" value="cHJpbmNl" />&nbsp;prince</label><br
/><label for="field.dog.3"><input class="radioType" id="field.dog.3"
    name="field.dog" type="radio" value="ZHVjaGVzcw==" />&nbsp;duchess</label><br
/><label for="field.dog.4"><input class="radioType" id="field.dog.4"
    name="field.dog" type="radio" value="bGFzc2ll" />&nbsp;lassie</label>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>

We’ll select an item by setting the appropriate fields in the request:

>>> request.form['field.dog-empty-marker'] = '1'
>>> request.form['field.dog'] = 'bGFzc2ll'
>>>
>>> widget = zope.app.form.browser.source.SourceRadioWidget(
...     dog, dog.source, request)
>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dog.0"><input class="radioType" id="field.dog.0"
    name="field.dog" type="radio" value="c3BvdA==" />&nbsp;spot</label><br
/><label for="field.dog.1"><input class="radioType" id="field.dog.1"
    name="field.dog" type="radio" value="Ym93c2Vy" />&nbsp;bowser</label><br
/><label for="field.dog.2"><input class="radioType" id="field.dog.2"
    name="field.dog" type="radio" value="cHJpbmNl" />&nbsp;prince</label><br
/><label for="field.dog.3"><input class="radioType" id="field.dog.3"
    name="field.dog" type="radio" value="ZHVjaGVzcw==" />&nbsp;duchess</label><br
/><label for="field.dog.4"><input class="radioType" checked="checked"
    id="field.dog.4" name="field.dog" type="radio" value="bGFzc2ll"
    />&nbsp;lassie</label>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>

For list-valued fields with items chosen from iterable sources, there are the SourceMultiSelectWidget and SourceOrderedMultiSelectWidget widgets. The latter widget includes support for re-ording the list items. SourceOrderedMultiSelectWidget is configured as the default widget for lists of choices.

If you don’t need ordering support through the web UI, then you can use the simpler SourceMultiSelectWidget:

>>> dogSource = SourceList([
...     u'spot', u'bowser', u'prince', u'duchess', u'lassie'])
>>> dogs = zope.schema.List(
...     __name__ = 'dogs',
...     title=u"Dogs",
...     value_type=zope.schema.Choice(
...         source=dogSource,
...     )
... )
>>> dogs = dogs.bind(object()) # give the field a context

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceMultiSelectWidget(
...     dogs, dogSource, request)

Let’s look at the rendered widget:

>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogs" multiple="multiple" name="field.dogs:list"
  size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>

We have no input yet:

>>> try:
...     widget.getInputValue()
... except zope.app.form.interfaces.MissingInputError:
...     print 'no input'
no input

Select an item:

>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> widget.getInputValue()
['lassie']

and another:

>>> request.form['field.dogs'] = ['cHJpbmNl', 'bGFzc2ll']
>>> widget.getInputValue()
['prince', 'lassie']

Finally, what does the widget look like now:

>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogs" multiple="multiple" name="field.dogs:list"
  size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option selected="selected" value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option selected="selected" value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>

An alternative for small numbers of items is to use SourceMultiCheckBoxWidget:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceMultiCheckBoxWidget(
...     dogs, dogSource, request)

The rendered widget:

>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dogs.0"><input class="checkboxType" id="field.dogs.0"
  name="field.dogs" type="checkbox" value="c3BvdA==" />&nbsp;spot</label><br
  /><label for="field.dogs.1"><input class="checkboxType" id="field.dogs.1"
      name="field.dogs" type="checkbox" value="Ym93c2Vy"
      />&nbsp;bowser</label><br
  /><label for="field.dogs.2"><input class="checkboxType" id="field.dogs.2"
      name="field.dogs" type="checkbox" value="cHJpbmNl"
      />&nbsp;prince</label><br
  /><label for="field.dogs.3"><input class="checkboxType" id="field.dogs.3"
      name="field.dogs" type="checkbox"
      value="ZHVjaGVzcw==" />&nbsp;duchess</label><br
  /><label for="field.dogs.4"><input class="checkboxType" id="field.dogs.4"
      name="field.dogs" type="checkbox" value="bGFzc2ll"
      />&nbsp;lassie</label>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>

We have no input yet:

>>> try:
...     widget.getInputValue()
... except zope.app.form.interfaces.MissingInputError:
...     print 'no input'
no input

Select an item:

>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> widget.getInputValue()
['lassie']

and another:

>>> request.form['field.dogs'] = ['c3BvdA==', 'bGFzc2ll']
>>> widget.getInputValue()
['spot', 'lassie']

Finally, what does the widget look like now:

>>> print widget() # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dogs.0"><input class="checkboxType" checked="checked"
  id="field.dogs.0" name="field.dogs" type="checkbox" value="c3BvdA=="
  />&nbsp;spot</label><br
  /><label for="field.dogs.1"><input class="checkboxType" id="field.dogs.1"
      name="field.dogs" type="checkbox" value="Ym93c2Vy"
      />&nbsp;bowser</label><br
  /><label for="field.dogs.2"><input class="checkboxType" id="field.dogs.2"
      name="field.dogs" type="checkbox" value="cHJpbmNl"
      />&nbsp;prince</label><br
  /><label for="field.dogs.3"><input class="checkboxType" id="field.dogs.3"
      name="field.dogs" type="checkbox"
      value="ZHVjaGVzcw==" />&nbsp;duchess</label><br
  /><label for="field.dogs.4"><input class="checkboxType" checked="checked"
      id="field.dogs.4" name="field.dogs" type="checkbox" value="bGFzc2ll"
      />&nbsp;lassie</label>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>

For list ordering support, use SourceOrderedMultiSelectWidget:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceOrderedMultiSelectWidget(
...     dogs, dogSource, request)

The widget is too complicated to show in complete rendered form here. Insted, we’ll inspect the properties of the widget:

>>> from zope.app.form.interfaces import MissingInputError
>>> try:
...     widget.getInputValue()
... except MissingInputError:
...     print 'no input'
no input

>>> widget.choices() == [
...     {'text': u'spot',    'value': 'c3BvdA=='},
...     {'text': u'bowser',  'value': 'Ym93c2Vy'},
...     {'text': u'prince',  'value': 'cHJpbmNl'},
...     {'text': u'duchess', 'value': 'ZHVjaGVzcw=='},
...     {'text': u'lassie',  'value': 'bGFzc2ll'}
... ]
True

>>> widget.selected()
[]

Let’s try out selecting items. Select one item:

>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> widget.selected() # doctest: +NORMALIZE_WHITESPACE
[{'text': u'lassie',  'value': 'bGFzc2ll'}]

>>> widget.getInputValue()
['lassie']

Select two items:

>>> request.form['field.dogs'] = ['c3BvdA==', 'bGFzc2ll']
>>> widget.selected()  # doctest: +NORMALIZE_WHITESPACE
[{'text': u'spot',    'value': 'c3BvdA=='},
 {'text': u'lassie',  'value': 'bGFzc2ll'}]

>>> widget.getInputValue()
['spot', 'lassie']

For set-valued fields, use SourceMultiSelectSetWidget:

>>> dogSet = zope.schema.Set(
...     __name__ = 'dogSet',
...     title=u"Dogs",
...     value_type=zope.schema.Choice(
...         source=dogSource,
...     )
... )
>>> dogSet = dogSet.bind(object()) # give the field a context
>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceMultiSelectSetWidget(
...     dogSet, dogSource, request)

>>> try:
...     widget.getInputValue()
... except zope.app.form.interfaces.MissingInputError:
...     print 'no input'
no input

>>> print widget()  # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogSet" multiple="multiple"
    name="field.dogSet:list" size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogSet-empty-marker" type="hidden" value="1" />
</div>

Let’s try out selecting items. Select one item:

>>> request.form['field.dogSet-empty-marker'] = '1'
>>> request.form['field.dogSet'] = ['bGFzc2ll']
>>> widget.getInputValue()
set(['lassie'])

Select two items:

>>> request.form['field.dogSet'] = ['c3BvdA==', 'bGFzc2ll']
>>> widget.getInputValue()
set(['spot', 'lassie'])

The rendered widget (still with the two items selected) looks like this:

>>> print widget()  # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogSet" multiple="multiple"
    name="field.dogSet:list" size="5" ><option selected="selected"
    value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option selected="selected" value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogSet-empty-marker" type="hidden" value="1" />
</div>

Source Widget Query Framework

An important aspect of sources is that they may have too many values to enumerate. Rather than listing all of the values, we, instead, provide interfaces for querying values and selecting values from query results. Matters are further complicated by the fact that different sources may have very different interfaces for querying them.

To make matters more interesting, a source may be an aggregation of several collections, each with their own querying facilities. An example of such a source is a principal source, where principals might come from a number of places, such as an LDAP database and ZCML-based principal definitions.

The default widgets for selecting values from sources use the following approach:

  • One or more query objects are obtained from the source by adapting the source to zope.schema.ISourceQueriables. If no adapter is obtained, then the source itself is assumed to be queriable.

  • For each queriable found, a zope.app.form.browser.interfaces.ISourceQueryView view is looked up. This view is used to obtain the HTML for displaying a query form. The view is also used to obtain search results.

Let’s start with a simple example. We have a very trivial source, which is basically a list:

>>> class SourceList(list):
...     zope.interface.implements(zope.schema.interfaces.ISource)

We need to register our ITerms view:

>>> zope.component.provideAdapter(
...     ListTerms,
...     (SourceList, zope.publisher.interfaces.browser.IBrowserRequest))

We aren’t going to provide an adapter to ISourceQueriables, so the source itself will be used as it’s own queriable. We need to provide a query view for the source:

>>> class ListQueryView:
...
...     zope.interface.implements(
...         zope.app.form.browser.interfaces.ISourceQueryView)
...     zope.component.adapts(
...         SourceList,
...         zope.publisher.interfaces.browser.IBrowserRequest,
...         )
...
...     def __init__(self, source, request):
...         self.source = source
...         self.request = request
...
...     def render(self, name):
...         return (
...             '<input name="%s.string">\n'
...             '<input type="submit" name="%s" value="Search">'
...             % (name, name)
...             )
...
...     def results(self, name):
...         if name in self.request:
...             search_string = self.request.get(name+'.string')
...             if search_string is not None:
...                 return [value
...                         for value in self.source
...                         if search_string in value
...                         ]
...         return None

>>> zope.component.provideAdapter(ListQueryView)

Now, we can define a choice field:

>>> dog = zope.schema.Choice(
...    __name__ = 'dog',
...    title=u"Dogs",
...    source=SourceList(['spot', 'bowser', 'prince', 'duchess', 'lassie']),
...    )

As before, we’ll just create the view directly:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceInputWidget(
...     dog, dog.source, request)

Now if we render the widget, we’ll see the input value (initially nothing) and a form elements for seaching for values:

>>> print widget()
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     Nothing
    </div>
  </div>
  <input type="hidden" name="field.dog.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

This shows that we haven’t selected a dog. We get a search box that we can type seach strings into. Let’s supply a search string. We do this by providing data in the form and by “selecting” the submit button:

>>> request.form['field.dog.displayed'] = u'y'
>>> request.form['field.dog.query.string'] = u'o'
>>> request.form['field.dog.query'] = u'Search'

Because the field is required, a non-selection is not valid. Thus, while the widget still hasInput, it will raise an error when you getInputValue:

>>> widget.hasInput()
True
>>> widget.getInputValue()
Traceback (most recent call last):
...
MissingInputError: ('dog', u'Dogs', None)

If the field is not required:

>>> dog.required = False

then as long as the field is displayed, the widget still has input but returns the field’s missing value:

>>> widget.hasInput()
True
>>> widget.getInputValue() # None

Now if we render the widget, we’ll see the search results:

>>> dog.required = True
>>> print widget()
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     Nothing
    </div>
  </div>
  <input type="hidden" name="field.dog.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
      </div> <!-- queryinput -->
      <div class="queryresults">
<select name="field.dog.query.selection">
<option value="Ym93c2Vy">bowser</option>
<option value="c3BvdA==">spot</option>
</select>
<input type="submit" name="field.dog.query.apply" value="Apply" />
      </div> <!-- queryresults -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

If we select an item:

>>> request.form['field.dog.displayed'] = u'y'
>>> del request.form['field.dog.query.string']
>>> del request.form['field.dog.query']
>>> request.form['field.dog.query.selection'] = u'c3BvdA=='
>>> request.form['field.dog.query.apply'] = u'Apply'

Then we’ll show the newly selected value:

>>> print widget()
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     spot
    </div>
  </div>
  <input type="hidden" name="field.dog" value="c3BvdA==" />
  <input type="hidden" name="field.dog.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

Note that we should have an input value now, since pressing the ‘Apply’ button provides us with input:

>>> widget.hasInput()
True

We should also be able to get the input value:

>>> widget.getInputValue()
'spot'

Now, let’s look at a more complicated example. We’ll define a source that combines multiple sources:

>>> class MultiSource:
...
...     zope.interface.implements(
...        zope.schema.interfaces.ISource,
...        zope.schema.interfaces.ISourceQueriables,
...        )
...
...     def __init__(self, *sources):
...         self.sources = [(unicode(i), s) for (i, s) in enumerate(sources)]
...
...     def __contains__(self, value):
...         for i, s in self.sources:
...             if value in s:
...                 return True
...         return False
...
...     def getQueriables(self):
...         return self.sources

This multi-source implements ISourceQueriables. It assumes that the sources it’s given are queriable and just returns the sources as the queryable objects.

We can reuse our terms view:

>>> zope.component.provideAdapter(
...     ListTerms,
...     (MultiSource, zope.publisher.interfaces.browser.IBrowserRequest))

Now, we’ll create a pet choice that combines dogs and cats:

>>> pet = zope.schema.Choice(
...    __name__ = 'pet',
...    title=u"Dogs and Cats",
...    source=MultiSource(
...      dog.source,
...      SourceList(['boots', 'puss', 'tabby', 'tom', 'tiger']),
...      ),
...    )

and a widget:

>>> widget = zope.app.form.browser.source.SourceInputWidget(
...     pet, pet.source, request)

Now if we display the widget, we’ll see search inputs for both dogs and cats:

>>> print widget()
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     Nothing
    </div>
  </div>
  <input type="hidden" name="field.pet.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

As before, we can perform a search:

>>> request.form['field.pet.displayed'] = u'y'
>>> request.form['field.pet.MQ__.string'] = u't'
>>> request.form['field.pet.MQ__'] = u'Search'

In which case, we’ll get some results:

>>> print widget() # doctest:
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     Nothing
    </div>
  </div>
  <input type="hidden" name="field.pet.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
      </div> <!-- queryinput -->
      <div class="queryresults">
<select name="field.pet.MQ__.selection">
<option value="Ym9vdHM=">boots</option>
<option value="dGFiYnk=">tabby</option>
<option value="dGlnZXI=">tiger</option>
<option value="dG9t">tom</option>
</select>
<input type="submit" name="field.pet.MQ__.apply" value="Apply" />
      </div> <!-- queryresults -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

from which we can choose:

>>> request.form['field.pet.displayed'] = u'y'
>>> del request.form['field.pet.MQ__.string']
>>> del request.form['field.pet.MQ__']
>>> request.form['field.pet.MQ__.selection'] = u'dGFiYnk='
>>> request.form['field.pet.MQ__.apply'] = u'Apply'

and get a selection:

>>> print widget()
<div class="value">
  <div class="row">
    <div class="label">
     Selected
    </div>
    <div class="field">
     tabby
    </div>
  </div>
  <input type="hidden" name="field.pet" value="dGFiYnk=" />
  <input type="hidden" name="field.pet.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

Note that we should have an input value now, since pressing the ‘Apply’ button provides us with input:

>>> widget.hasInput()
True

and we can get the input value:

>>> widget.getInputValue()
'tabby'

There’s a display widget, which doesn’t use queriables, since it doesn’t assign values:

>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceDisplayWidget(
...     pet, pet.source, request)
>>> print widget()
Nothing
>>> from zope.app.form.browser.interfaces import IBrowserWidget
>>> IBrowserWidget.providedBy(widget)
True

>>> widget.setRenderedValue('tabby')
>>> print widget()
tabby

Like any good display widget, input is not required:

>>> widget.required
False

If we specify a list of choices:

>>> pets = zope.schema.List(__name__ = 'pets', title=u"Pets",
...                         value_type=pet)

when a widget is computed for the field, a view will be looked up for the field and the source, where, in this case, the field is a list field. We’ll just call the widget factory directly:

>>> widget = zope.app.form.browser.source.SourceListInputWidget(
...     pets, pets.value_type.source, request)

If we render the widget:

>>> print widget()
<div class="value">
  <input type="hidden" name="field.pets.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

Here the output looks very similar to the simple choice case. We get a search input for each source. In this case, we don’t show any inputs (TODO we probably should make it clearer that there are no selected values.)

As before, we can search one of the sources:

>>> request.form['field.pets.displayed'] = u'y'
>>> request.form['field.pets.MQ__.string'] = u't'
>>> request.form['field.pets.MQ__'] = u'Search'

In which case, we’ll get some results:

>>> print widget()
<div class="value">
  <input type="hidden" name="field.pets.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
      </div> <!-- queryinput -->
      <div class="queryresults">
<select name="field.pets.MQ__.selection:list" multiple>
<option value="Ym9vdHM=">boots</option>
<option value="dGFiYnk=">tabby</option>
<option value="dGlnZXI=">tiger</option>
<option value="dG9t">tom</option>
</select>
<input type="submit" name="field.pets.MQ__.apply" value="Apply" />
      </div> <!-- queryresults -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

from which we can select some values:

>>> request.form['field.pets.displayed'] = u'y'
>>> del request.form['field.pets.MQ__.string']
>>> del request.form['field.pets.MQ__']
>>> request.form['field.pets.MQ__.selection'] = [
...     u'dGFiYnk=', u'dGlnZXI=', u'dG9t']
>>> request.form['field.pets.MQ__.apply'] = u'Apply'

Which then leads to the selections appearing as widget selections:

>>> print widget()
<div class="value">
  <input type="checkbox" name="field.pets.checked:list" value="dGFiYnk=" />
  tabby
  <input type="hidden" name="field.pets:list" value="dGFiYnk=" />
  <br />
  <input type="checkbox" name="field.pets.checked:list" value="dGlnZXI=" />
  tiger
  <input type="hidden" name="field.pets:list" value="dGlnZXI=" />
  <br />
  <input type="checkbox" name="field.pets.checked:list" value="dG9t" />
  tom
  <input type="hidden" name="field.pets:list" value="dG9t" />
  <br />
  <input type="submit" name="field.pets.remove" value="Remove" />
  <br />
  <input type="hidden" name="field.pets.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

We can get the selected values:

>>> widget.getInputValue()
['tabby', 'tiger', 'tom']

We now see the values we selected. We also have checkboxes and buttons that allow us to remove selections:

>>> request.form['field.pets.displayed'] = u'y'
>>> request.form['field.pets'] = [u'dGFiYnk=', u'dGlnZXI=', u'dG9t']
>>> del request.form['field.pets.MQ__.selection']
>>> del request.form['field.pets.MQ__.apply']
>>> request.form['field.pets.checked'] = [u'dGFiYnk=', u'dG9t']
>>> request.form['field.pets.remove'] = u'Remove'

>>> print widget()
<div class="value">
  <input type="checkbox" name="field.pets.checked:list" value="dGlnZXI=" />
  tiger
  <input type="hidden" name="field.pets:list" value="dGlnZXI=" />
  <br />
  <input type="submit" name="field.pets.remove" value="Remove" />
  <br />
  <input type="hidden" name="field.pets.displayed" value="y" />
  <div class="queries">
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
    <div class="query">
      <div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
      </div> <!-- queryinput -->
    </div> <!-- query -->
  </div> <!-- queries -->
</div> <!-- value -->

Using vocabulary-dependent widgets with sources

if you have a widget that uses old-style vocabularies but don’t have the time to rewrite it for sources, all is not lost! The wrapper IterableSourceVocabulary can be used to make sources and ITerms look like a vocabulary. This allows us to use vocabulary-based widgets with sources instead of vocabularies.

Usage:

>>> from zope.schema.vocabulary import SimpleTerm

>>> values  = [u'a', u'b', u'c']
>>> tokens  = [ '0',  '1',  '2']
>>> titles  = [u'A', u'B', u'C']

>>> terms = [SimpleTerm(values[i], token=tokens[i], title=titles[i]) \
...     for i in range(0,len(values))]

>>> class TestSource(list):
...     zope.interface.implements(zope.schema.interfaces.IIterableSource)
>>> source = TestSource(values)

>>> class TestTerms(object):
...     zope.interface.implements(ITerms)
...     def __init__(self, source, request):
...         pass
...     def getTerm(self, value):
...         index = values.index(value)
...         return terms[index]
...     def getValue(self, token):
...         index = tokens.index(token)
...         return values[index]

>>> zope.component.provideAdapter(
...     TestTerms,
...     (TestSource, zope.publisher.interfaces.browser.IBrowserRequest))

>>> from zope.app.form.browser.source import IterableSourceVocabulary
>>> request = TestRequest()
>>> vocab = IterableSourceVocabulary(source, request)
>>> from zope.interface.verify import verifyClass, verifyObject
>>> verifyClass(zope.schema.interfaces.IVocabularyTokenized, \
...     IterableSourceVocabulary)
True
>>> verifyObject(zope.schema.interfaces.IVocabularyTokenized, vocab)
True

>>> len(vocab)
3
>>> (u'a' in vocab) and (u'b' in vocab) and (u'c' in vocab)
True
>>> [value for value in vocab] == terms
True
>>> term = vocab.getTerm(u'b')
>>> (term.value, term.token, term.title)
(u'b', '1', u'B')
>>> term = vocab.getTermByToken('2')
>>> (term.value, term.token, term.title)
(u'c', '2', u'C')

Internationalization

Forms are fully internationalized. The field names, descriptions, labels, and hints are all automatically translated if they are made i18n messages in the schema.

Let’s take this simple add form…

>>> print http(r"""
... GET /+/addfieldcontent.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False)
HTTP/1.1 200 OK
...

with an error…

>>> print http(r"""
... POST /+/addfieldcontent.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Content-Length: 670
... Content-Type: multipart/form-data; boundary=---------------------------19588947601368617292863650127
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.title"
...
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.description"
...
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.somenumber"
...
... 0
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="UPDATE_SUBMIT"
...
... Hinzufxgen
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="add_input_name"
...
...
... -----------------------------19588947601368617292863650127--
... """, handle_errors=False)
HTTP/1.1 200 OK
...
          There are <strong>1</strong> input errors.
...

Translated

And now the add form in German:

>>> print http(r"""
... GET /+/addfieldcontent.html HTTP/1.1
... Accept-Language: de
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False)
HTTP/1.1 200 OK
...Felderinhalt hinzuf...
...Eine kurz...Titel...
...Eine ausf...Beschreibung...
...Irgendeine Zahl...
...Irgendeine Liste...
...Irgendeine Liste hinzuf...
...Auffrischen...
...Hinzuf...
...Objektname...

The same with an input error:

>>> print http(r"""
... POST /+/addfieldcontent.html HTTP/1.1
... Accept-Language: de
... Authorization: Basic mgr:mgrpw
... Content-Length: 670
... Content-Type: multipart/form-data; boundary=---------------------------19588947601368617292863650127
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.title"
...
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.description"
...
...
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="field.somenumber"
...
... 0
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="UPDATE_SUBMIT"
...
... Hinzufxgen
... -----------------------------19588947601368617292863650127
... Content-Disposition: form-data; name="add_input_name"
...
...
... -----------------------------19588947601368617292863650127--
... """, handle_errors=False)
HTTP/1.1 200 OK
...Felderinhalt hinzuf...
...Ein Fehler ist aufgetreten...
...Es gab <strong>1</strong> Eingabefehler...
...Eine kurz...Titel...
...Erforderliche Eingabe fehlt...
...Eine ausf...Beschreibung...
...Irgendeine Zahl...
...Irgendeine Liste...
...hinzuf...
...Auffrischen...
...Hinzuf...
...Objektname...

Source widgets

Titles of terms are translated by the source widgets. Let’s create a source for which the terms create message ids:

>>> import zc.sourcefactory.basic
>>> from zope.i18nmessageid import MessageFactory
>>> _ = MessageFactory('coffee')
>>> class Coffees(zc.sourcefactory.basic.BasicSourceFactory):
...     def getValues(self):
...         return ['arabica', 'robusta', 'liberica', 'excelsa']
...     def getTitle(self, value):
...         return _(value, default='Translated %s' % value)
>>> import zope.schema
>>> from zope.publisher.browser import TestRequest
>>> coffee = zope.schema.Choice(
...    __name__ = 'coffee',
...    title=u"Kinds of coffee beans",
...    source=Coffees())
>>> request = TestRequest()
>>> widget = zope.app.form.browser.source.SourceDisplayWidget(
...     coffee, coffee.source, request)
>>> print widget()
Nothing
>>> from zope.app.form.browser.interfaces import IBrowserWidget
>>> IBrowserWidget.providedBy(widget)
True
>>> widget.setRenderedValue('arabica')
>>> print widget()
Translated arabica

CHANGES

3.8.0 (2009-05-24)

  • Use standard properties instead of zope.cachedescriptors.

  • Require zope.browser 1.1 instead of zope.app.container for IAdding.

3.7.3 (2009-05-11)

  • Fixed invalid markup.

3.7.2 (2009-03-12)

  • Fixed bug where OrderedMultiSelectWidget did not respect the widgets size attribute.

  • Fixed bug in SequenceWidget where it crashed while trying to iterate a missing_value (None in most of cases) on _getRenderedValue.

  • Adapt to removal of deprecated interfaces from zope.component.interfaces. The IView was moved to zope.publisher and we use our custom IWidgetFactory interface instead of removed zope.component.interfaces.IViewFactory.

  • Fix tests to work on Python 2.6.

3.7.1 (2009-01-31)

  • Adapt to the upcoming zope.schema release 3.5.1 which will also silence the spurious set failures.

3.7.0 (2008-12-11)

  • use zope.browser.interfaces.ITerms instead of zope.app.form.browser.interfaces

  • Depending on zope.schema>=3.5a1 which uses the builtin set instead of the sets module.

3.6.4 (2008-11-26)

  • The URIDisplayWidget doesn’t render an anchor for empty/None values.

3.6.3 (2008-10-15)

  • Get rid of deprecated usage of LayerField from zope.app.component.back35, replaced by zope.configuration.fields.GlobalInterface.

3.6.2 (2008-09-08)

  • Fixed restructured text in doc tests to unbreak the PyPI page.

(3.6.1 skipped due to a typo)

3.6.0 (2008-08-22)

  • Dropdown widgets display an item for the missing value even if the field is required when no value is selected. See zope/app/form/browser/README.txt on how to switch this off for BBB.

  • Source select widgets for required fields are now required as well. They used not to be required on the assumption that some value would be selected by the browser, which had always been wrong except for dropdown widgets.

3.5.0 (2008-06-05)

  • Translate the title on SequenceWidget’s “Add <title>” button.

  • No longer uses zapi.

3.4.2 (2008-02-07)

  • Made display widgets for sources translate message IDs correctly.

3.4.1 (2007-10-31)

  • Resolve ZopeSecurityPolicy deprecation warning.

3.4.0 (2007-10-24)

  • zope.app.form now supports Python2.5

  • Initial release independent of the main Zope tree.

Before 3.4

This package was part of the Zope 3 distribution and did not have its own CHANGES.txt. For earlier changes please refer to either our subversion log or the CHANGES.txt of earlier Zope 3 releases.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zope.app.form-3.8.0.zip (216.5 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page