skip to navigation
skip to content

Not Logged In

zope.app.form 3.6.0

The Original Zope 3 Form Framework

Latest Version: 3.8.0

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
===============

.. contents::

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::

  

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::

  

  

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::

  

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::

  


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``::

    

    
    

    

    

    
    

    
    
    

    

    
        
        
    

    

    


    

    

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``::

    
    Poll results
    
Poll results
OptionResultsDescription
Option Result Option
``vote.zpt``:: Poll voting
Poll voting
Option Option
============= 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.app.form.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:: >>> import zope.publisher.interfaces.browser >>> import zope.app.form.browser.interfaces >>> from zope.schema.vocabulary import SimpleTerm >>> class ListTerms: ... ... zope.interface.implements( ... zope.app.form.browser.interfaces.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
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()
If we set the displayed value for the widget, that value is marked as selected:: >>> widget.setRenderedValue("duchess") >>> print widget()
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
 spot



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




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
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
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




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




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 >>> from sets import Set >>> 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
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
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 ( ... '\n' ... '' ... % (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()
Selected
Nothing
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()
Selected
Nothing
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()
Selected
spot
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()
Selected
Nothing
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:
Selected
Nothing
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()
Selected
tabby
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()
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()
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()
tabby
tiger
tom

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()
tiger

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) >>> from zope.app.form.browser.interfaces import ITerms >>> 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 1 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 1 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.6.1 (unreleased) ================== 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 " 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.</PRE> <table class="list" style="margin-bottom: 10px;"> <tr> <th>File</th> <th>Type</th> <th>Py Version</th> <th>Uploaded on</th> <th style="text-align: right;">Size</th> <th style="text-align: right;"># downloads</th> </tr> <tr class="odd"> <td> <span style="white-space: nowrap;"> <a href="http://pypi.python.org/packages/source/z/zope.app.form/zope.app.form-3.6.0.tar.gz#md5=cc619f937d3f8e034892242d78d4c534">zope.app.form-3.6.0.tar.gz</a> (<a title="MD5 Digest" href="/pypi?:action=show_md5&digest=cc619f937d3f8e034892242d78d4c534">md5</a>, <a title="PGP Signature" href="http://pypi.python.org/packages/source/z/zope.app.form/zope.app.form-3.6.0.tar.gz.asc">pgp</a>) </span> </td> <td style="white-space: nowrap;"> Source </td> <td> </td> <td>2008-08-22 11:32:21</td> <td style="text-align: right;">132KB</td> <td style="text-align: right;">979</td> </tr> <tr><td id="last" colspan="5"/></tr> </table> <ul class="nodot"> <li> <strong>Author:</strong> <span>Zope Corporation and Contributors <zope3-dev at zope org></span> </li> <!-- The <th> elements below are a terrible terrible hack for setuptools --> <li> <strong>Home Page:</strong> <!-- <th>Home Page --> <a href="http://cheeseshop.python.org/pypi/zope.app.form">http://cheeseshop.python.org/pypi/zope.app.form</a> </li> <li> <strong>Keywords:</strong> <span>zope3 form widget zcml</span> </li> <li> <strong>License:</strong> <span>ZPL 2.1</span> </li> <!-- TODO: add link to products in follow dependencies... --> <li> <strong>Categories</strong> <ul class="nodot"> <li> <a href="/pypi?:action=browse&c=5">Development Status :: 5 - Production/Stable</a> </li> <li> <a href="/pypi?:action=browse&c=21">Environment :: Web Environment</a> </li> <li> <a href="/pypi?:action=browse&c=515">Framework :: Zope3</a> </li> <li> <a href="/pypi?:action=browse&c=30">Intended Audience :: Developers</a> </li> <li> <a href="/pypi?:action=browse&c=89">License :: OSI Approved :: Zope Public License</a> </li> <li> <a href="/pypi?:action=browse&c=104">Natural Language :: English</a> </li> <li> <a href="/pypi?:action=browse&c=156">Operating System :: OS Independent</a> </li> <li> <a href="/pypi?:action=browse&c=214">Programming Language :: Python</a> </li> <li> <a href="/pypi?:action=browse&c=326">Topic :: Internet :: WWW/HTTP</a> </li> </ul> </li> <li> <strong>Package Index Owner:</strong> <span>baijum, J1m, ctheune, projekt01, srichter, philikon, ignas, benji, fdrake, chrism, zagy, mgedmin, ccomb, pcardune, tlotze, sidnei, faassen, nadako, hathawsh, chrisw, icemac, hannosch, tseaver, gary, malthe</span> </li> <li> <strong><a href="http://usefulinc.com/doap">DOAP</a> record:</strong> <a href="/pypi?:action=doap&name=zope.app.form&version=3.6.0">zope.app.form-3.6.0.xml</a> </li> </ul> </div> </div> <div id="footer"><div id="credits"> <a href="http://www.python.org/about/website">Website maintained by the Python community</a><br/> <a href="http://www.xs4all.com/" title="Web and email hosting provided by xs4all, Netherlands">hosting by xs4all</a> / <a href="http://www.pollenation.net/" title="Design and content management system by Pollenation Internet, Yorkshire">design by pollenation</a> </div> Copyright © 1990-2007, <a href="http://www.python.org/psf">Python Software Foundation</a><br/> <a href="http://www.python.org/about/legal">Legal Statements</a> </div> </div> </div> </body> </html>