zope.app.form-4.0.2/ 0000755 0001750 0001750 00000000000 11340453341 013521 5 ustar sidnei sidnei zope.app.form-4.0.2/PKG-INFO 0000644 0001750 0001750 00000016410 11340453341 014620 0 ustar sidnei sidnei Metadata-Version: 1.0
Name: zope.app.form
Version: 4.0.2
Summary: The Original Zope 3 Form Framework
Home-page: http://pypi.python.org/pypi/zope.app.form
Author: Zope Corporation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: This package provides the old form 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``. The widgets that were defined in here were moved to
``zope.formlib``. Version 4.0 and newer are maintained for backwards
compatibility reasons only.
Detailed documentation:
=======
CHANGES
=======
4.0.2 (2010-01-22)
==================
- Seems like 4.0.1 was released already. Brown bag.
4.0.1 (2010-01-08)
==================
- Import 'escape' for backwards compatibility as packages turn out to be
importing this too, even though it's actually from the Python standard
library.
- Widget documentation is now on PyPI too.
4.0 (2010-01-08)
================
- The widget implementations have been moved to zope.formlib. This
makes this package depend on zope.formlib. The dependency of zope.formlib
on this package has been broken.
3.12.1 (2009-12-22)
===================
- Added missing zope.datetime dependency.
3.12.0 (2009-12-22)
===================
- Use zope.browserpage in favor of zope.app.pagetemplate.
3.11.1 (2009-12-22)
===================
- Prefer zope.testing.doctest over doctestunit and adjust test output to newer
zope.schema release.
3.11.0 (2009-12-18)
===================
- Use zope.component.testing in favor of zope.app.testing where possible.
- Define dummy standard_macros for test purposes. This reduces the test
dependencies by zope.app.basicskin and zope.browserresource.
- Removed the zope.app.container and zope.app.publisher testing dependencies.
- Refactored code to remove zope.app.component dependency.
- Made the tests independent of zope.app.locales.
- Reduce zope.app test dependencies by avoiding zope.app.securitypolicy and
zope.app.zcmlfiles.
3.10.0 (2009-12-17)
===================
- Avoid the ``zope.app.basicskin`` dependency, by defining our own FormMacros.
3.9.0 (2009-10-08)
==================
- Internationalized 'Invalid value' used with ConversionError
- Added dependency on transaction and test dependency on zope.app.component.
- Moved dependencies on ZODB3 and zope.location to the test extra.
- Reduced the dependency on zope.app.publisher to a dependency on
zope.browsermenu plus a test dependency on zope.browserpage.
3.8.1 (2009-07-23)
==================
- Fix unittest failure due to translation update.
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
" 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.
Keywords: zope3 form widget zcml
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Programming Language :: Python
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Framework :: Zope3
zope.app.form-4.0.2/setup.py 0000644 0001750 0001750 00000006113 11340453312 015232 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
# This package is developed by the Zope Toolkit project, documented here:
# http://docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Setup for zope.app.form package
$Id: setup.py 81002 2007-10-24 01:19:47Z srichter $
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name='zope.app.form',
version = '4.0.2',
author='Zope Corporation and Contributors',
author_email='zope-dev@zope.org',
description='The Original Zope 3 Form Framework',
long_description=(
read('README.txt')
+ '\n\n' +
'Detailed documentation:\n'
+ '\n\n' +
read('CHANGES.txt')
),
keywords = "zope3 form widget zcml",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Zope Public License',
'Programming Language :: Python',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
'Framework :: Zope3'],
url='http://pypi.python.org/pypi/zope.app.form',
license='ZPL 2.1',
packages=find_packages('src'),
package_dir = {'': 'src'},
namespace_packages=['zope', 'zope.app'],
extras_require={'test': [
'ZODB3',
'zc.sourcefactory',
'zope.container',
'zope.principalregistry',
'zope.site',
'zope.traversing',
'zope.app.appsetup',
'zope.app.publication',
'zope.app.testing',
]},
install_requires=[
"setuptools",
"transaction",
"zope.formlib >= 4.0",
"zope.browser>=1.1",
"zope.browserpage>=3.10.1",
"zope.browsermenu",
"zope.component",
"zope.configuration",
"zope.datetime",
"zope.exceptions",
"zope.i18n",
"zope.interface",
"zope.proxy",
"zope.publisher",
"zope.schema>=3.5.1dev",
"zope.security",
],
include_package_data = True,
zip_safe = False,
)
zope.app.form-4.0.2/COPYRIGHT.txt 0000644 0001750 0001750 00000000712 11340453312 015630 0 ustar sidnei sidnei Copyright (c) 2007 Zope Corporation and contributors.
All Rights Reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
FOR A PARTICULAR PURPOSE.
zope.app.form-4.0.2/setup.cfg 0000644 0001750 0001750 00000000073 11340453341 015342 0 ustar sidnei sidnei [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
zope.app.form-4.0.2/README.txt 0000644 0001750 0001750 00000000551 11340453312 015216 0 ustar sidnei sidnei This package provides the old form 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``. The widgets that were defined in here were moved to
``zope.formlib``. Version 4.0 and newer are maintained for backwards
compatibility reasons only.
zope.app.form-4.0.2/LICENSE.txt 0000644 0001750 0001750 00000004027 11340453312 015345 0 ustar sidnei sidnei Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.app.form-4.0.2/buildout.cfg 0000644 0001750 0001750 00000000146 11340453312 016030 0 ustar sidnei sidnei [buildout]
develop = .
parts = test
[test]
recipe = zc.recipe.testrunner
eggs = zope.app.form [test]
zope.app.form-4.0.2/src/ 0000755 0001750 0001750 00000000000 11340453341 014310 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/ 0000755 0001750 0001750 00000000000 11340453312 015263 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/__init__.py 0000644 0001750 0001750 00000000310 11340453312 017366 0 ustar sidnei sidnei # this is a namespace package
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
zope.app.form-4.0.2/src/zope/app/ 0000755 0001750 0001750 00000000000 11340453312 016043 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/__init__.py 0000644 0001750 0001750 00000000310 11340453312 020146 0 ustar sidnei sidnei # this is a namespace package
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
zope.app.form-4.0.2/src/zope/app/form/ 0000755 0001750 0001750 00000000000 11340453312 017006 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/testing.py 0000644 0001750 0001750 00000001745 11340453312 021044 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2007 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""zope.app.form common test related classes/functions/objects.
$Id: testing.py 72343 2007-02-03 06:04:09Z baijum $
"""
__docformat__ = "reStructuredText"
import os
from zope.app.testing.functional import ZCMLLayer
AppFormLayer = ZCMLLayer(
os.path.join(os.path.split(__file__)[0], 'ftesting.zcml'),
__name__, 'AppFormLayer', allow_teardown=True)
zope.app.form-4.0.2/src/zope/app/form/utility.py 0000644 0001750 0001750 00000021247 11340453312 021071 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form utility functions
In Zope 2's formulator, forms provide a basic mechanism for
organizing collections of fields and providing user interfaces for
them, especially editing interfaces.
In Zope 3, formulator's forms are replaced by Schema (See
zope.schema). In addition, the Formulator fields have been replaced by
schema fields and form widgets. Schema fields just express the semantics
of data values. They contain no presentation logic or parameters.
Widgets are views on fields that take care of presentation. The widget
view names represent styles that can be selected by applications to
customise the presentation. There can also be custom widgets with
specific parameters.
This module provides some utility functions that provide some of the
functionality of formulator forms that isn't handled by schema,
fields, or widgets.
$Id: utility.py 107385 2009-12-30 20:25:24Z faassen $
"""
__docformat__ = 'restructuredtext'
from zope import security
from zope.security.proxy import Proxy
from zope.proxy import isProxy
from zope.interface.interfaces import IMethod
from zope.security.interfaces import ForbiddenAttribute, Unauthorized
from zope.formlib.interfaces import WidgetsError, MissingInputError
from zope.formlib.interfaces import InputErrors
from zope.formlib.interfaces import IInputWidget, IDisplayWidget
# BBB
from zope.formlib.utility import (
setUpWidget,
setUpWidgets,
applyWidgetsChanges,
_fieldlist,
no_value,
_widgetHasStickyValue)
def setUpEditWidgets(view, schema, source=None, prefix=None,
ignoreStickyValues=False, names=None, context=None,
degradeInput=False, degradeDisplay=False):
"""Sets up widgets to collect input on a view.
See `setUpWidgets` for details on `view`, `schema`, `prefix`,
`ignoreStickyValues`, `names`, and `context`.
`source`, if specified, is an object from which initial widget values are
read. If source is not specified, the view context is used as the source.
`degradeInput` is a flag that changes the behavior when a user does not
have permission to edit a field in the names. By default, the function
raises Unauthorized. If degradeInput is True, the field is changed to
an IDisplayWidget.
`degradeDisplay` is a flag that changes the behavior when a user does not
have permission to access a field in the names. By default, the function
raises Unauthorized. If degradeDisplay is True, the field is removed from
the form.
Returns a list of names, equal to or a subset of the names that were
supposed to be drawn, with uninitialized undrawn fields missing.
"""
if context is None:
context = view.context
if source is None:
source = view.context
security_proxied = isProxy(source, Proxy)
res_names = []
for name, field in _fieldlist(names, schema):
try:
value = field.get(source)
except ForbiddenAttribute:
raise
except AttributeError:
value = no_value
except Unauthorized:
if degradeDisplay:
continue
else:
raise
if field.readonly:
viewType = IDisplayWidget
else:
if security_proxied:
is_accessor = IMethod.providedBy(field)
if is_accessor:
set_name = field.writer.__name__
authorized = security.canAccess(source, set_name)
else:
set_name = name
authorized = security.canWrite(source, name)
if not authorized:
if degradeInput:
viewType = IDisplayWidget
else:
raise Unauthorized(set_name)
else:
viewType = IInputWidget
else:
# if object is not security proxied, might be a standard
# adapter without a registered checker. If the feature of
# paying attention to the users ability to actually set a
# field is decided to be a must-have for the form machinery,
# then we ought to change this case to have a deprecation
# warning.
viewType = IInputWidget
setUpWidget(view, name, field, viewType, value, prefix,
ignoreStickyValues, context)
res_names.append(name)
return res_names
def setUpDisplayWidgets(view, schema, source=None, prefix=None,
ignoreStickyValues=False, names=None, context=None,
degradeDisplay=False):
"""Sets up widgets to display field values on a view.
See `setUpWidgets` for details on `view`, `schema`, `prefix`,
`ignoreStickyValues`, `names`, and `context`.
`source`, if specified, is an object from which initial widget values are
read. If source is not specified, the view context is used as the source.
`degradeDisplay` is a flag that changes the behavior when a user does not
have permission to access a field in the names. By default, the function
raises Unauthorized. If degradeDisplay is True, the field is removed from
the form.
Returns a list of names, equal to or a subset of the names that were
supposed to be drawn, with uninitialized undrawn fields missing.
"""
if context is None:
context = view.context
if source is None:
source = view.context
res_names = []
for name, field in _fieldlist(names, schema):
try:
value = field.get(source)
except ForbiddenAttribute:
raise
except AttributeError:
value = no_value
except Unauthorized:
if degradeDisplay:
continue
else:
raise
setUpWidget(view, name, field, IDisplayWidget, value, prefix,
ignoreStickyValues, context)
res_names.append(name)
return res_names
def viewHasInput(view, schema, names=None):
"""Returns ``True`` if the any of the view's widgets contain user input.
`schema` specifies the set of fields that correspond to the view widgets.
`names` can be specified to provide a subset of these fields.
"""
for name, field in _fieldlist(names, schema):
if getattr(view, name + '_widget').hasInput():
return True
return False
def getWidgetsData(view, schema, names=None):
"""Returns user entered data for a set of `schema` fields.
The return value is a map of field names to data values.
`view` is the view containing the widgets. `schema` is the schema that
defines the widget fields. An optional `names` argument can be provided
to specify an alternate list of field values to return. If `names` is
not specified, or is ``None``, `getWidgetsData` will attempt to return
values for all of the fields in the schema.
A requested field value may be omitted from the result for one of two
reasons:
- The field is read only, in which case its widget will not have
user input.
- The field is editable and not required but its widget does not
contain user input.
If a field is required and its widget does not have input, `getWidgetsData`
raises an error.
A widget may raise a validation error if it cannot return a value that
satisfies its field's contraints.
Errors, if any, are collected for all fields and reraised as a single
`WidgetsError`.
"""
result = {}
errors = []
for name, field in _fieldlist(names, schema):
widget = getattr(view, name + '_widget')
if IInputWidget.providedBy(widget):
if widget.hasInput():
try:
result[name] = widget.getInputValue()
except InputErrors, error:
errors.append(error)
elif field.required:
errors.append(MissingInputError(
name, widget.label, 'the field is required'))
if errors:
raise WidgetsError(errors, widgetsData=result)
return result
zope.app.form-4.0.2/src/zope/app/form/interfaces.py 0000644 0001750 0001750 00000002576 11340453312 021515 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Validation Exceptions
$Id: interfaces.py 107371 2009-12-30 18:36:02Z faassen $
"""
__docformat__ = 'restructuredtext'
# this moved to zope.formlib.interfaces
from zope.formlib.interfaces import (IWidgetInputError,
WidgetInputError,
MissingInputError,
ConversionError,
InputErrors,
ErrorContainer,
WidgetsError,
IWidget,
IInputWidget,
IDisplayWidget,
IWidgetFactory)
zope.app.form-4.0.2/src/zope/app/form/browser/ 0000755 0001750 0001750 00000000000 11340453312 020471 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/browser/metadirectives.py 0000644 0001750 0001750 00000021577 11340453312 024067 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form and Widget specific 'browser' ZCML namespace interfaces
$Id: metadirectives.py 104906 2009-10-08 06:06:50Z tlotze $
"""
__docformat__ = 'restructuredtext'
from zope.interface import Interface
from zope.configuration.fields import GlobalObject, GlobalInterface
from zope.configuration.fields import Tokens, Path, Bool, PythonIdentifier
from zope.configuration.fields import MessageID
from zope.schema import Text, TextLine, Id
from zope.security.zcml import Permission
from zope.browsermenu.field import MenuField
class ICommonInformation(Interface):
"""
Common information for all successive directives
"""
name = TextLine(
title=u"Name",
description=u"The name of the generated view.",
required=True
)
schema = GlobalInterface(
title=u"Schema",
description=u"The schema from which the form is generated.",
required=True
)
for_ = GlobalInterface(
title=u"Interface",
description=u"""
The interface this page (view) applies to.
The view will be for all objects that implement this
interface. The schema is used if the for attribute is not
specified.
If the for attribute is specified, then the objects views must
implement or be adaptable to the schema.""",
required=False
)
permission = Permission(
title=u"Permission",
description=u"The permission needed to use the view.",
required=True
)
layer = GlobalInterface(
title=u"Layer",
description=u"The later the view is in. Default: 'default'",
required=False
)
template = Path(
title=u"Template",
description=u"An alternate template to use for the form.",
required=False
)
class_ = GlobalObject(
title=u"Class",
description=u"""
A class to provide custom widget definitions or methods to be
used by a custom template.
This class is used as a mix-in class. As a result, it needn't
subclass any special classes, such as BrowserView.""",
required=False
)
class ICommonFormInformation(ICommonInformation):
"""
Common information for browser forms
"""
label = MessageID(
title=u"Label",
description=u"A label to be used as the heading for the form.",
required=False
)
menu = MenuField(
title=u"The browser menu to include the form in.",
description=u"""
Many views are included in menus. It's convenient to name the
menu in the page directive, rather than having to give a
separate menuItem directive.""",
required=False
)
title = MessageID(
title=u"Menu title",
description=u"The browser menu label for the form.",
required=False
)
fields = Tokens(
title=u"Fields",
description=u"""
Here you can specify the names of the fields you wish to display.
The order in this list is also the order the fields will
be displayed in. If this attribute is not specified, all schema fields
will be displayed in the order specified in the schema itself.""",
required=False,
value_type=PythonIdentifier()
)
class ICommonAddInformation(Interface):
"""
Common information for add forms
"""
content_factory = GlobalObject(
title=u"Content factory",
description=u"""
An object to call to create new content objects.
This attribute isn't used if a class is specified that
implements createAndAdd.""",
required=False
)
content_factory_id = Id(
title=u"Content factory id",
description=u"A factory id to create new content objects",
required = False,
)
arguments = Tokens(
title=u"Arguments",
description=u"""
A list of field names to supply as positional arguments to the
factory.""",
required=False,
value_type=PythonIdentifier()
)
keyword_arguments = Tokens(
title=u"Keyword arguments",
description=u"""
A list of field names to supply as keyword arguments to the
factory.""",
required=False,
value_type=PythonIdentifier()
)
set_before_add = Tokens(
title=u"Set before add",
description=u"""
A list of fields to be assigned to the newly created object
before it is added.""",
required=False,
value_type=PythonIdentifier(),
)
set_after_add = Tokens(
title=u"Set after add",
description=u"""
A list of fields to be assigned to the newly created object
after it is added.""",
required=False,
value_type=PythonIdentifier()
)
class IFormDirective(ICommonFormInformation):
"""
Define an automatically generated form.
The form directive does nto require the data to be stored in its context,
but leaves the storing procedure to the to a method.
"""
class_ = GlobalObject(
title=u"Class",
description=u"""
A class to provide the `getData()` and `setData()` methods or
completely custom methods to be used by a custom template.
This class is used as a mix-in class. As a result, it needn't
subclass any special classes, such as BrowserView.""",
required=True
)
class IEditFormDirective(ICommonFormInformation):
"""
Define an automatically generated edit form
The editform directive creates and registers a view for editing
an object based on a schema.
"""
class ISubeditFormDirective(ICommonInformation):
"""
Define a subedit form
"""
label = TextLine(
title=u"Label",
description=u"A label to be used as the heading for the form.",
required=False
)
fulledit_path = TextLine(
title=u"Path (relative URL) to the full edit form",
required=False
)
fulledit_label = MessageID(
title=u"Label of the full edit form",
required=False
)
class IAddFormDirective(ICommonFormInformation, ICommonAddInformation):
"""
Define an automatically generated add form
The addform directive creates and registers a view for adding an
object based on a schema.
Adding an object is a bit trickier than editing an object, because
the object the schema applies to isn't available when forms are
being rendered. The addform directive provides a customization
interface to overcome this difficulty.
See zope.app.form.browser.interfaces.IAddFormCustomization.
"""
description = MessageID(
title=u"A longer description of the add form.",
description=u"""
A UI may display this with the item or display it when the
user requests more assistance.""",
required=False
)
class ISchemaDisplayDirective(ICommonFormInformation):
"""
Define an automatically generated display form.
The schemadisplay directive creates and registers a view for
displaying an object based on a schema.
"""
title = MessageID(
title=u"The browser menu label for the edit form",
description=u"This attribute defaults to 'Edit'.",
required=False
)
class IWidgetSubdirective(Interface):
"""Register custom widgets for a form.
This directive allows you to quickly generate custom widget directives for
a form.
Besides the two required arguments, field and class, you can specify any
amount of keyword arguments, e.g. style='background-color:#fefefe;'.
The keywords will be stored as attributes on the widget instance. To see
which keywords are sensible, you should look at the code of the specified
widget class.
"""
field = TextLine(
title=u"Field Name",
description=u"""
The name of the field/attribute/property for which this widget will be
used.""",
required=True,
)
class_ = GlobalObject(
title=u"Widget Class",
description=u"""The class that will create the widget.""",
required=False,
)
# Arbitrary keys and values are allowed to be passed to the CustomWidget.
IWidgetSubdirective.setTaggedValue('keyword_arguments', True)
zope.app.form-4.0.2/src/zope/app/form/browser/form.txt 0000644 0001750 0001750 00000015117 11340453312 022202 0 ustar sidnei sidnei =============
Generic Forms
=============
The `browser:form` allows the developer to use the form and widget framework
without relying on a particular context object. Instead, it is up to the
developer to implement two simple methods that handle the retrieval and
mutation of the data in form of a dictionary.
But I am getting ahead of myself. We first need to define a schema that we
would like to use for our form:
>>> import zope.interface
>>> import zope.schema
>>> class IName(zope.interface.Interface):
... """The name of a person."""
...
... first = zope.schema.TextLine(
... title=u"First Name",
... required=False)
...
... last = zope.schema.TextLine(
... title=u"Last Name",
... required=True)
Now we are almost ready to create the form view. But first we have to create a
class that knows how to get and set values for the fields described by the
schema. The system calls for a class (that will be used as a mixin) that
implements a method called `getData()` that returns a dictionary mapping field
names to values and a second method called `setData(data)` that takes a data
dictionary as argument and handles the data in any way fit. In our case, let's
store the data in a global attribute called name:
>>> name = ['John', 'Doe']
>>> class DataHandler(object):
...
... def getData(self):
... global name
... return {'first': name[0], 'last': name[1]}
...
... def setData(self, data):
... global name
... name[0] = data['first']
... name[1] = data['last']
... return u"Saved changes."
We now imitate the form-directive's behavior and create the view class:
>>> from zope.app.form.browser.formview import FormView
>>> View = type('View', (DataHandler, FormView), {'schema': IName})
To initialize the view, you still need a context and a request. The context is
useful because it gives you a location, so that you can look up local
components to store the data, such as the principal annotations. In our case
we do not care about the context, so it will be just `None`:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = View(None, request)
We can now look at the widgets and see that the data was correctly loaded:
>>> view.first_widget()
u''
>>> view.last_widget()
u''
Now when a request is sent in, the data is transmitted in the form
>>> request.form['field.first'] = u'Stephan'
>>> request.form['field.last'] = u'Richter'
>>> request.form['UPDATE_SUBMIT'] = u''
and as soon as the `update()` method is called
>>> view.update()
u'Saved changes.'
the global name variable is changed:
>>> name
[u'Stephan', u'Richter']
And that's pretty much all that there is to it. The rest behaves exactly like
an edit form, from which the form view was derived.
Of course you can also completely overwrite the `update()` method like for the
edit view removing the requirement to implement the `getData()` and
`setData()` methods.
Using the `browser:form` directive
==================================
Let's now see how the form directive works. The first task is to load the
necessary meta-configuration:
>>> from zope.configuration import xmlconfig
>>> import zope.component
>>> context = xmlconfig.file('meta.zcml', zope.component)
>>> import zope.app.form.browser
>>> context = xmlconfig.file('meta.zcml', zope.app.form.browser, context)
Before we run the directive, make sure that no view exists:
>>> class IAnything(zope.interface.Interface):
... pass
>>> class Anything(object):
... zope.interface.implements(IAnything)
>>> from zope.publisher.browser import TestRequest
>>> from zope.component import queryMultiAdapter
>>> queryMultiAdapter((Anything(), TestRequest()), name='name.html')
Now that we know that the view did not exist before the registration, let's
execute the form directive:
>>> import sys
>>> sys.modules['form'] = type(
... 'Module', (),
... {'DataHandler': DataHandler,
... 'IAnything': IAnything,
... 'IName': IName})()
>>> context = xmlconfig.string('''
...
...
...
...
...
...
...
... ''', context)
and try to look up the view again:
>>> queryMultiAdapter(
... (Anything(), TestRequest()), name='name.html') #doctest:+ELLIPSIS
Now, if I do not specify my own template, and my class does not overwrite the
`update()` method, then the class *must* implement `getData()` and
`setData(data)`, otherwise a configuration error is raised:
>>> class NewDataHandler(object):
...
... def getData(self):
... return {}
>>> sys.modules['form'].NewDataHandler = NewDataHandler
>>> context = xmlconfig.string('''
...
...
...
...
...
... ''', context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 6.6
ConfigurationError: You must specify a class that implements
`getData()` and `setData()`, if you do not
overwrite `update()`.
Now we need to clean up afterwards.
>>> del sys.modules['form']
zope.app.form-4.0.2/src/zope/app/form/browser/widget.py 0000644 0001750 0001750 00000001723 11340453312 022331 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001-2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Browser Widget Definitions
$Id: widget.py 107818 2010-01-08 19:14:50Z faassen $
"""
__docformat__ = 'restructuredtext'
# BBB
from zope.formlib.widget import (
quoteattr,
BrowserWidget,
SimpleInputWidget,
DisplayWidget,
UnicodeDisplayWidget,
renderTag,
renderElement,
escape,
setUp,
tearDown)
zope.app.form-4.0.2/src/zope/app/form/browser/formview.py 0000644 0001750 0001750 00000005470 11340453312 022707 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form View Classes
$Id: formview.py 107371 2009-12-30 18:36:02Z faassen $
"""
__docformat__ = 'restructuredtext'
import transaction
from zope.formlib.interfaces import WidgetsError, IInputWidget
from zope.app.form.utility import setUpWidgets, applyWidgetsChanges
from zope.app.form.browser.editview import EditView
from zope.app.form.browser.i18n import _
from zope.app.form.browser.submit import Update
class Data(dict):
"""Dictionary wrapper to make keys available as attributes."""
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class FormView(EditView):
def getData(self):
"""Get the data for the form.
This method should return a dictionary mapping field names to values.
"""
NotImplemented, 'Must be implemented by a specific form class'
def setData(self, data):
"""Set the data gotten from a form.
The data will be a dictionary of fieldnames to values.
May return a status message.
"""
NotImplemented, 'Must be implemented by a specific form class'
def _setUpWidgets(self):
self.data = Data(self.getData())
setUpWidgets(
self, self.schema, IInputWidget, initial=self.data,
names=self.fieldNames)
def update(self):
if self.update_status is not None:
# We've been called before. Just return the status we previously
# computed.
return self.update_status
status = ''
if Update in self.request:
try:
changed = applyWidgetsChanges(
self, self.schema, target=self.data, names=self.fieldNames)
except WidgetsError, errors:
self.errors = errors
status = _("An error occurred.")
transaction.doom()
else:
if changed:
status = self.setData(self.data)
setUpWidgets(
self, self.schema, IInputWidget, initial=self.data,
ignoreStickyValues=True, names=self.fieldNames)
self.update_status = status
return status
zope.app.form-4.0.2/src/zope/app/form/browser/add.py 0000644 0001750 0001750 00000014020 11340453312 021570 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Add Form View class
$Id: add.py 107371 2009-12-30 18:36:02Z faassen $
"""
__docformat__ = 'restructuredtext'
import sys
import zope.component
from zope.component.interfaces import IFactory
from zope.event import notify
from zope.interface import Interface
from zope.schema.interfaces import ValidationError
from zope.security.checker import defineChecker, NamesChecker
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.lifecycleevent import ObjectCreatedEvent, ObjectModifiedEvent
from zope.lifecycleevent import Attributes
from zope.app.form.utility import setUpWidgets, getWidgetsData
from zope.formlib.interfaces import IInputWidget, WidgetsError
from zope.app.form.browser.i18n import _
from zope.browserpage.simpleviewclass import SimpleViewClass
from zope.browserpage import ViewPageTemplateFile
from editview import EditView
from submit import Update
class AddView(EditView):
"""Simple edit-view base class.
Subclasses should provide a schema attribute defining the schema
to be edited.
"""
def _setUpWidgets(self):
setUpWidgets(self, self.schema, IInputWidget, names=self.fieldNames)
def update(self):
if self.update_status is not None:
# We've been called before. Just return the previous result.
return self.update_status
if Update in self.request:
self.update_status = ''
try:
data = getWidgetsData(self, self.schema, names=self.fieldNames)
self.createAndAdd(data)
except WidgetsError, errors:
self.errors = errors
self.update_status = _("An error occurred.")
return self.update_status
self.request.response.redirect(self.nextURL())
return self.update_status
def create(self, *args, **kw):
"""Do the actual instantiation."""
return self._factory(*args, **kw)
def createAndAdd(self, data):
"""Add the desired object using the data in the data argument.
The data argument is a dictionary with the data entered in the form.
"""
args = []
if self._arguments:
for name in self._arguments:
args.append(data[name])
kw = {}
if self._keyword_arguments:
for name in self._keyword_arguments:
if name in data:
kw[str(name)] = data[name]
content = self.create(*args, **kw)
errors = []
if self._set_before_add:
adapted = self.schema(content)
for name in self._set_before_add:
if name in data:
field = self.schema[name]
try:
field.set(adapted, data[name])
except ValidationError:
errors.append(sys.exc_info()[1])
if errors:
raise WidgetsError(*errors)
notify(ObjectCreatedEvent(content))
content = self.add(content)
if self._set_after_add:
adapted = self.schema(content)
for name in self._set_after_add:
if name in data:
if data[name] is not None:
field = self.schema[name]
try:
field.set(adapted, data[name])
except ValidationError:
errors.append(sys.exc_info()[1])
# We have modified the object, so we need to publish an
# object-modified event:
description = Attributes(self.schema, *self._set_after_add)
notify(ObjectModifiedEvent(content, description))
if errors:
raise WidgetsError(*errors)
return content
def add(self, content):
return self.context.add(content)
def nextURL(self):
return self.context.nextURL()
# helper for factory resp. content_factory handling
def _getFactory(self):
# get factory or factory id
factory = self.__dict__.get('_factory_or_id', self._factory_or_id)
if type(factory) is str: # factory id
return zope.component.getUtility(IFactory, factory, self.context)
else:
return factory
def _setFactory(self, value):
self.__dict__['_factory_or_id'] = value
def AddViewFactory(name, schema, label, permission, layer,
template, default_template, bases, for_,
fields, content_factory, arguments,
keyword_arguments, set_before_add, set_after_add):
class_ = SimpleViewClass(
template, used_for=schema, bases=bases, name=name)
class_.schema = schema
class_.label = label
class_.fieldNames = fields
class_._factory_or_id = content_factory
class_._factory = property(_getFactory, _setFactory)
class_._arguments = arguments
class_._keyword_arguments = keyword_arguments
class_._set_before_add = set_before_add
class_._set_after_add = set_after_add
class_.generated_form = ViewPageTemplateFile(default_template)
defineChecker(class_,
NamesChecker(
("__call__", "__getitem__",
"browserDefault", "publishTraverse"),
permission,
)
)
if layer is None:
layer = IDefaultBrowserLayer
s = zope.component.getGlobalSiteManager()
s.registerAdapter(class_, (for_, layer), Interface, name)
zope.app.form-4.0.2/src/zope/app/form/browser/exception.py 0000644 0001750 0001750 00000001507 11340453312 023044 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form-related exception views
$Id: exception.py 107385 2009-12-30 20:25:24Z faassen $
"""
# BBB implementation moved to zope.formlib.exception
from zope.formlib.exception import WidgetInputErrorView
zope.app.form-4.0.2/src/zope/app/form/browser/edit.pt 0000644 0001750 0001750 00000004035 11340453312 021765 0 ustar sidnei sidnei
zope.app.form-4.0.2/src/zope/app/form/browser/interfaces.py 0000644 0001750 0001750 00000007433 11340453312 023175 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form and Widget Interfaces
$Id: interfaces.py 107398 2009-12-30 22:26:34Z faassen $
"""
__docformat__ = 'restructuredtext'
from zope.interface import Interface
from zope.schema import TextLine, Bool
from zope.formlib.interfaces import IWidget, IInputWidget
# BBB: ITerms are also used by z3c.form and possibly other form
# frameworks, so it was moved to zope.browser.interfaces and it's
# preferred to import from there now.
from zope.browser.interfaces import ITerms
from zope.formlib.interfaces import (
IBrowserWidget, ISimpleInputWidget, ITextBrowserWidget,
IWidgetInputErrorView, ISourceQueryView)
class IFormCollaborationView(Interface):
"""Views that collaborate to create a single form.
When a form is applied, the changes in the form need to
be applied to individual views, which update objects as
necessary.
"""
def __call__():
"""Render the view as a part of a larger form.
Form input elements should be included, prefixed with the
prefix given to setPrefix.
`form` and `submit` elements should not be included. They
will be provided for the larger form.
"""
def setPrefix(prefix):
"""Set the `prefix` used for names of input elements
Element names should begin with the given `prefix`,
followed by a dot.
"""
def update():
"""Update the form with data from the request."""
class IAddFormCustomization(Interface):
"""API for add form customization.
Classes supplied when defining add forms may need to override some
of these methods.
In particular, when the context of an add form is not an `IAdding`,
a subclass needs to override `nextURL` and one of `add` or
`createAndAdd`.
To see how all this fits together, here's pseudo code for the
update() method of the form:
def update(self):
data = # a dict
self.createAndAdd(data)
self.request.response.redirect(self.nextURL())
def createAndAdd(self, data):
content =
content = self.add(content)
"""
def createAndAdd(data):
"""Create a new object from the given data and the resulting object.
The data argument is a dictionary with values supplied by the form.
If any user errors occur, they should be collected into a list
and raised as a ``WidgetsError``.
(For the default implementation, see pseudo-code in class docs.)
"""
def add(content):
"""Add the given content.
This method is overridden when the context of the add form is
not an `IAdding`. In this case, the class that customizes the
form must take over adding the object.
The default implementation returns `self.context.add(content)`,
i.e. it delegates to the `IAdding` view.
"""
def nextURL():
"""Return the URL to be displayed after the add operation.
This can be relative to the view's context.
The default implementation returns `self.context.nextURL()`,
i.e. it delegates to the `IAdding` view.
"""
zope.app.form-4.0.2/src/zope/app/form/browser/source.py 0000644 0001750 0001750 00000002162 11340453312 022344 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Source widgets support
$Id: source.py 107398 2009-12-30 22:26:34Z faassen $
"""
# BBB
from zope.formlib.source import (
SourceDisplayWidget,
SourceSequenceDisplayWidget,
SourceInputWidget,
SourceListInputWidget,
IterableSourceVocabulary,
SourceSelectWidget,
SourceDropdownWidget,
SourceRadioWidget,
SourceMultiSelectWidget,
SourceOrderedMultiSelectWidget,
SourceMultiSelectSetWidget,
SourceMultiSelectFrozenSetWidget,
SourceMultiCheckBoxWidget)
zope.app.form-4.0.2/src/zope/app/form/browser/macros.py 0000644 0001750 0001750 00000003131 11340453312 022325 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""API Documentation macros
$Id: macros.py 106723 2009-12-17 23:16:34Z hannosch $
"""
__docformat__ = 'restructuredtext'
from zope.component import getMultiAdapter
from zope.interface import implements
from zope.interface.common.mapping import IItemMapping
from zope.publisher.browser import BrowserView
class FormMacros(BrowserView):
implements(IItemMapping)
macro_pages = (
'view_macros',
'widget_macros',
'addform_macros',
)
aliases = {
'view': 'page',
'dialog': 'page',
'addingdialog': 'page',
}
def __getitem__(self, key):
key = self.aliases.get(key, key)
context = self.context
request = self.request
for name in self.macro_pages:
page = getMultiAdapter((context, request), name=name)
try:
v = page[key]
except KeyError:
pass
else:
return v
raise KeyError(key)
zope.app.form-4.0.2/src/zope/app/form/browser/display.pt 0000644 0001750 0001750 00000001700 11340453312 022501 0 ustar sidnei sidnei
Display something
Extra top
Extra bottom
zope.app.form-4.0.2/src/zope/app/form/browser/__init__.py 0000644 0001750 0001750 00000007143 11340453312 022607 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Browser widgets
$Id: __init__.py 107377 2009-12-30 19:46:00Z faassen $
"""
__docformat__ = 'restructuredtext'
# the implementation of widgets has moved to zope.formlib.widgets
# import directly from there instead.
from zope.formlib.widget import BrowserWidget, DisplayWidget
from zope.formlib.widget import UnicodeDisplayWidget
from zope.formlib.widgets import TextWidget, BytesWidget
from zope.formlib.widgets import TextAreaWidget, BytesAreaWidget
from zope.formlib.widgets import PasswordWidget, FileWidget
from zope.formlib.widgets import ASCIIWidget, ASCIIAreaWidget
from zope.formlib.widgets import IntWidget, FloatWidget
from zope.formlib.widgets import DecimalWidget
from zope.formlib.widgets import DatetimeWidget, DateWidget
from zope.formlib.widgets import DatetimeI18nWidget
from zope.formlib.widgets import DateI18nWidget
from zope.formlib.widgets import DatetimeDisplayWidget
from zope.formlib.widgets import DateDisplayWidget
from zope.formlib.widgets import BytesDisplayWidget
from zope.formlib.widgets import ASCIIDisplayWidget
from zope.formlib.widgets import URIDisplayWidget
# Widgets for boolean fields
from zope.formlib.widgets import CheckBoxWidget
from zope.formlib.widgets import BooleanRadioWidget
from zope.formlib.widgets import BooleanSelectWidget
from zope.formlib.widgets import BooleanDropdownWidget
# Choice and Sequence Display Widgets
from zope.formlib.widgets import ItemDisplayWidget
from zope.formlib.widgets import ItemsMultiDisplayWidget
from zope.formlib.widgets import SetDisplayWidget
from zope.formlib.widgets import ListDisplayWidget
# Widgets for fields with vocabularies.
# Note that these are only dispatchers for the widgets below.
from zope.formlib.widgets import ChoiceDisplayWidget
from zope.formlib.widgets import ChoiceInputWidget
from zope.formlib.widgets import CollectionDisplayWidget
from zope.formlib.widgets import CollectionInputWidget
from zope.formlib.widgets import ChoiceCollectionDisplayWidget
from zope.formlib.widgets import ChoiceCollectionInputWidget
# Widgets that let you choose a single item from a list
# These widgets are multi-views on (field, vocabulary)
from zope.formlib.widgets import SelectWidget
from zope.formlib.widgets import DropdownWidget
from zope.formlib.widgets import RadioWidget
# Widgets that let you choose several items from a list
# These widgets are multi-views on (field, vocabulary)
from zope.formlib.widgets import MultiSelectWidget
from zope.formlib.widgets import MultiSelectSetWidget
from zope.formlib.widgets import MultiSelectFrozenSetWidget
from zope.formlib.widgets import MultiCheckBoxWidget
from zope.formlib.widgets import OrderedMultiSelectWidget
# Widgets that let you enter several items in a sequence
# These widgets are multi-views on (sequence type, value type)
from zope.formlib.widgets import SequenceWidget
from zope.formlib.widgets import TupleSequenceWidget
from zope.formlib.widgets import ListSequenceWidget
from zope.formlib.widgets import SequenceDisplayWidget
from zope.formlib.widgets import ObjectWidget
zope.app.form-4.0.2/src/zope/app/form/browser/add.pt 0000644 0001750 0001750 00000004456 11340453312 021577 0 ustar sidnei sidnei
zope.app.form-4.0.2/src/zope/app/form/browser/boolwidgets.py 0000644 0001750 0001750 00000001666 11340453312 023376 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Browser widgets for items
$Id: boolwidgets.py 107385 2009-12-30 20:25:24Z faassen $
"""
# BBB implementation moved to zope.formlib.boolwidgets
from zope.formlib.boolwidgets import (
CheckBoxWidget,
BooleanRadioWidget,
BooleanSelectWidget,
BooleanDropdownWidget,
BooleanDisplayWidget)
zope.app.form-4.0.2/src/zope/app/form/browser/itemswidgets.py 0000644 0001750 0001750 00000002761 11340453312 023561 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Browser widgets for items
$Id: itemswidgets.py 107385 2009-12-30 20:25:24Z faassen $
"""
__docformat__ = 'restructuredtext'
# BBB the implementation has moved to zope.formlib.itemswidgets
from zope.formlib.itemswidgets import (
ChoiceDisplayWidget,
ChoiceInputWidget,
CollectionDisplayWidget,
CollectionInputWidget,
ChoiceCollectionDisplayWidget,
ChoiceCollectionInputWidget,
TranslationHook,
ItemsWidgetBase,
SingleDataHelper,
MultiDataHelper,
ItemsWidgetBase,
ItemDisplayWidget,
ItemsMultiDisplayWidget,
ListDisplayWidget,
SetDisplayWidget,
ItemsEditWidgetBase,
EXPLICIT_EMPTY_SELECTION,
SelectWidget,
DropdownWidget,
RadioWidget,
ItemsMultiEditWidgetBase,
MultiSelectWidget,
MultiSelectSetWidget,
MultiSelectFrozenSetWidget,
OrderedMultiSelectWidget,
MultiCheckBoxWidget)
zope.app.form-4.0.2/src/zope/app/form/browser/metaconfigure.py 0000644 0001750 0001750 00000025553 11340453312 023705 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Configuration handlers for forms and widgets
$Id: metaconfigure.py 107376 2009-12-30 19:21:24Z faassen $
"""
__docformat__ = 'restructuredtext'
import os
import zope.component
from zope.security.checker import CheckerPublic
from zope.interface import implementedBy
from zope.configuration.exceptions import ConfigurationError
from zope.browser.interfaces import IAdding
from zope.schema import getFieldNamesInOrder
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.browsermenu.metaconfigure import menuItemDirective
from zope.formlib.widget import CustomWidgetFactory
from zope.app.form.browser.i18n import _
from zope.formlib.interfaces import IInputWidget, IDisplayWidget
from zope.formlib.interfaces import IWidgetFactory
from add import AddView, AddViewFactory
from editview import EditView, EditViewFactory
from formview import FormView
from schemadisplay import DisplayView, DisplayViewFactory
class BaseFormDirective(object):
# to be overriden by the subclasses
view = None
default_template = None
# default basic information
for_ = None
layer = IDefaultBrowserLayer
permission = CheckerPublic
template = None
class_ = None
# default form information
title = None
label = None
menu = None
fields = None
def __init__(self, _context, **kwargs):
self._context = _context
for key, value in kwargs.items():
if not (value is None and hasattr(self, key)):
setattr(self, key, value)
self._normalize()
self._widgets = {}
def widget(self, _context, field, **kw):
attrs = kw
class_ = attrs.pop("class_", None)
# Try to do better than accepting the string value by looking through
# the interfaces and trying to find the field, so that we can use
# 'fromUnicode()'
if isinstance(class_, type):
ifaces = implementedBy(class_)
for name, value in kw.items():
for iface in ifaces:
if name in iface:
attrs[name] = iface[name].fromUnicode(value)
break
if class_ is None:
# The _default_widget_factory is required to allow the
# directive to be given without a "class"
# attribute. This can be used to override some of the
# presentational attributes of the widget implementation.
class_ = self._default_widget_factory
# don't wrap a factory into a factory
if IWidgetFactory.providedBy(class_):
factory = class_
else:
factory = CustomWidgetFactory(class_, **attrs)
self._widgets[field+'_widget'] = factory
def _processWidgets(self):
if self._widgets:
customWidgetsObject = type('CustomWidgetsMixin', (object,),
self._widgets)
self.bases = self.bases + (customWidgetsObject,)
def _normalize(self):
if self.for_ is None:
self.for_ = self.schema
if self.class_ is None:
self.bases = (self.view,)
else:
self.bases = (self.class_, self.view)
if self.template is not None:
self.template = os.path.abspath(str(self.template))
if not os.path.isfile(self.template):
raise ConfigurationError("No such file", self.template)
else:
self.template = self.default_template
self.names = getFieldNamesInOrder(self.schema)
if self.fields:
for name in self.fields:
if name not in self.names:
raise ValueError("Field name is not in schema",
name, self.schema)
else:
self.fields = self.names
def _args(self):
permission = self.permission
if permission == 'zope.Public':
# Translate public permission to CheckerPublic
permission = CheckerPublic
return (self.name, self.schema, self.label, permission,
self.layer, self.template, self.default_template,
self.bases, self.for_, self.fields)
def _discriminator(self):
return ('view', self.for_, self.name, IBrowserRequest,
self.layer)
class AddFormDirective(BaseFormDirective):
view = AddView
default_template = 'add.pt'
for_ = IAdding
# default add form information
description = None
content_factory_id = None
content_factory = None
arguments = None
keyword_arguments = None
set_before_add = None
set_after_add = None
def _default_widget_factory(self, field, request):
# `field` is a bound field
return zope.component.getMultiAdapter(
(field, request), IInputWidget)
def _handle_menu(self):
if self.menu or self.title:
if (not self.menu) or (not self.title):
raise ValueError("If either menu or title are specified, "
"they must both be specified")
# Add forms are really for IAdding components, so do not use
# for=self.schema.
menuItemDirective(
self._context, self.menu, self.for_, '@@' + self.name,
self.title, permission=self.permission, layer=self.layer,
description=self.description)
def _handle_arguments(self, leftover=None):
schema = self.schema
fields = self.fields
arguments = self.arguments
keyword_arguments = self.keyword_arguments
set_before_add = self.set_before_add
set_after_add = self.set_after_add
if leftover is None:
leftover = fields
if arguments:
missing = [n for n in arguments if n not in fields]
if missing:
raise ValueError("Some arguments are not included in the form",
missing)
optional = [n for n in arguments if not schema[n].required]
if optional:
raise ValueError("Some arguments are optional, use"
" keyword_arguments for them",
optional)
leftover = [n for n in leftover if n not in arguments]
if keyword_arguments:
missing = [n for n in keyword_arguments if n not in fields]
if missing:
raise ValueError(
"Some keyword_arguments are not included in the form",
missing)
leftover = [n for n in leftover if n not in keyword_arguments]
if set_before_add:
missing = [n for n in set_before_add if n not in fields]
if missing:
raise ValueError(
"Some set_before_add are not included in the form",
missing)
leftover = [n for n in leftover if n not in set_before_add]
if set_after_add:
missing = [n for n in set_after_add if n not in fields]
if missing:
raise ValueError(
"Some set_after_add are not included in the form",
missing)
leftover = [n for n in leftover if n not in set_after_add]
self.set_after_add += leftover
else:
self.set_after_add = leftover
def _handle_content_factory(self):
if self.content_factory is None:
self.content_factory = self.content_factory_id
def __call__(self):
self._processWidgets()
self._handle_menu()
self._handle_content_factory()
self._handle_arguments()
self._context.action(
discriminator=self._discriminator(),
callable=AddViewFactory,
args=self._args()+(self.content_factory, self.arguments,
self.keyword_arguments,
self.set_before_add, self.set_after_add),
)
class EditFormDirectiveBase(BaseFormDirective):
view = EditView
def _default_widget_factory(self, field, request):
# `field` is a bound field
if field.readonly:
iface = IDisplayWidget
else:
iface = IInputWidget
return zope.component.getMultiAdapter(
(field, request), iface)
class EditFormDirective(EditFormDirectiveBase):
default_template = 'edit.pt'
title = _('Edit')
def _handle_menu(self):
if self.menu:
menuItemDirective(
self._context, self.menu, self.for_ or self.schema,
'@@' + self.name, self.title, permission=self.permission,
layer=self.layer)
def __call__(self):
self._processWidgets()
self._handle_menu()
self._context.action(
discriminator=self._discriminator(),
callable=EditViewFactory,
args=self._args(),
)
class FormDirective(EditFormDirective):
view = FormView
def __init__(self, _context, **kwargs):
super(FormDirective, self).__init__(_context, **kwargs)
attrs = self.class_.__dict__.keys()
if 'template' not in kwargs.keys() and 'update' not in attrs and \
('getData' not in attrs or 'setData' not in attrs):
raise ConfigurationError(
"You must specify a class that implements `getData()` "
"and `setData()`, if you do not overwrite `update()`.")
class SubeditFormDirective(EditFormDirectiveBase):
default_template = 'subedit.pt'
# default subedit form directive
fulledit_path = None
fulledit_label = None
def __call__(self):
self._processWidgets()
self._context.action(
discriminator = self._discriminator(),
callable = EditViewFactory,
args = self._args()+(self.fulledit_path, self.fulledit_label),
)
class SchemaDisplayDirective(EditFormDirective):
view = DisplayView
default_template = 'display.pt'
def __call__(self):
self._processWidgets()
self._handle_menu()
self._context.action(
discriminator = self._discriminator(),
callable = DisplayViewFactory,
args = self._args()+(self.menu,)
)
zope.app.form-4.0.2/src/zope/app/form/browser/tests/ 0000755 0001750 0001750 00000000000 11340453312 021633 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_browserwidget.py 0000644 0001750 0001750 00000001546 11340453312 026141 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test Browser Widget
$Id: test_browserwidget.py 107392 2009-12-30 21:07:14Z faassen $
"""
# BBB
from zope.formlib.tests.test_browserwidget import (
BrowserWidgetTest,
SimpleInputWidgetTest,
TestWidget,
Test)
zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_directives.py 0000644 0001750 0001750 00000025335 11340453312 025415 0 ustar sidnei sidnei #############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Form Directives Tests
$Id: test_directives.py 107371 2009-12-30 18:36:02Z faassen $
"""
import unittest
from cStringIO import StringIO
from zope import component
from zope.component.testing import PlacelessSetup
from zope.configuration.xmlconfig import xmlconfig, XMLConfig
from zope.traversing.interfaces import TraversalError
from zope.interface import Interface, implements
from zope.publisher.browser import TestRequest
from zope.schema import TextLine, Int
from zope.app.form.browser import TextWidget
from zope.app.form.tests import utils
template = """
%s
"""
request = TestRequest()
class Schema(Interface):
text = TextLine(
title=u'Text',
description=u'Nice text',
required=False)
class IC(Schema): pass
class Ob(object):
implements(IC)
unwrapped_ob = Ob()
ob = utils.securityWrap(unwrapped_ob, IC)
class ISomeWidget(Interface):
displayWidth = Int(
title=u"Display Width",
default=20,
required=True)
class SomeWidget(TextWidget):
implements(ISomeWidget)
class Test(PlacelessSetup, unittest.TestCase):
def setUp(self):
super(Test, self).setUp()
import zope.component
XMLConfig('meta.zcml', zope.component)()
import zope.app.form.browser
XMLConfig('meta.zcml', zope.app.form.browser)()
import zope.browsermenu
XMLConfig('meta.zcml', zope.browsermenu)()
from zope.traversing.adapters import DefaultTraversable
from zope.traversing.interfaces import ITraversable
component.provideAdapter(DefaultTraversable, (None,), ITraversable)
def testAddForm(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='add.html'),
None)
xmlconfig(StringIO(template % ("""
""")))
v = component.getMultiAdapter((ob, request), name='add.html')
# expect to fail as standard macros are not configured
self.assertRaises(TraversalError, v)
def testEditForm(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='edit.html'),
None)
xmlconfig(StringIO(template % ("""
""")))
v = component.getMultiAdapter((ob, request), name='edit.html')
# expect to fail as standard macros are not configured
self.assertRaises(TraversalError, v)
def testEditFormWithMenu(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='edit.html'),
None)
xmlconfig(StringIO(template % ('''
''')))
v = component.queryMultiAdapter((ob, request), name='edit.html')
# expect to fail as standard macros are not configured
self.assertRaises(TraversalError, v)
def testSchemaDisplay(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='view.html'),
None)
xmlconfig(StringIO(template % ('''
''')))
v = component.queryMultiAdapter((ob, request), name='view.html')
# expect to fail as standard macros are not configured
self.assertRaises(TraversalError, v)
def testAddFormWithWidget(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='add.html'),
None)
xmlconfig(StringIO(template % ('''
''')), )
view = component.queryMultiAdapter((ob, request), name='add.html')
self.assert_(hasattr(view, 'text_widget'))
self.assert_(isinstance(view.text_widget, SomeWidget))
self.assertEqual(view.text_widget.extra, u'foo')
self.assertEqual(view.text_widget.displayWidth, 30)
def testEditFormWithWidget(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='edit.html'),
None)
xmlconfig(StringIO(template % ('''
''')), )
view = component.queryMultiAdapter((ob, request), name='edit.html')
self.assert_(hasattr(view, 'text_widget'))
self.assert_(isinstance(view.text_widget, SomeWidget))
self.assertEqual(view.text_widget.extra, u'foo')
self.assertEqual(view.text_widget.displayWidth, 30)
def testSchemaDisplayWithWidget(self):
self.assertEqual(
component.queryMultiAdapter((ob, request), name='view.html'),
None)
xmlconfig(StringIO(template % ('''
''')))
view = component.queryMultiAdapter((ob, request), name='view.html')
self.assert_(hasattr(view, 'text_widget'))
self.assert_(isinstance(view.text_widget, SomeWidget))
self.assertEqual(view.text_widget.extra, u'foo')
self.assertEqual(view.text_widget.displayWidth, 30)
def test_suite():
loader=unittest.TestLoader()
return loader.loadTestsFromTestCase(Test)
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_functional_editview.py 0000644 0001750 0001750 00000006551 11340453312 027315 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Editview tests
$Id: test_functional_editview.py 81040 2007-10-24 15:27:12Z srichter $
"""
import unittest
import transaction
from persistent import Persistent
import zope.security.checker
from zope.interface import Interface, implements
from zope.schema import TextLine
from zope.traversing.api import traverse
from zope.app.form.browser.editview import EditView
from zope.app.form.testing import AppFormLayer
from zope.app.form.browser.tests.support import *
from zope.app.testing.functional import BrowserTestCase
class IFoo(Interface):
optional_text = TextLine(required=False)
required_text = TextLine(required=True)
class Foo(Persistent):
implements(IFoo)
class Test(BrowserTestCase):
def setUp(self):
BrowserTestCase.setUp(self)
registerEditForm(IFoo)
defineSecurity(Foo, IFoo)
def test_rollback_on_error(self):
"""Tests rollback when a widget error occurs.
When one or more errors are generated by input widgets, the current
transaction should be rolledback to ensure object integrity.
"""
self.getRootFolder()['foo'] = Foo()
self.getRootFolder()['foo'].required_text = u'initial required'
self.getRootFolder()['foo'].optional_text = u'initial optional'
transaction.commit()
# submit form with legal value for optional_text and invalid for
# required_text
old_update = EditView.update
try:
def new_update(self):
# This update changes something after form validation has failed.
# Side effects like this should not be committed.
# http://www.zope.org/Collectors/Zope3-dev/655
result = old_update(self)
self.context.required_text = u'changed after form validation'
return result
EditView.update = new_update
response = self.publish('/foo/edit.html', form={
'field.optional_text': u'',
'field.required_text': u'',
'UPDATE_SUBMIT': ''})
self.assertEqual(response.getStatus(), 200)
finally:
EditView.update = old_update
# confirm that one errors exists
self.assert_(patternExists(
'There are 1 input errors.', response.getBody()))
# confirm that foo was not modified
foo = traverse(self.getRootFolder(), 'foo')
self.assertEquals(foo.required_text, u'initial required')
self.assertEquals(foo.optional_text, u'initial optional')
def test_suite():
suite = unittest.TestSuite()
Test.layer = AppFormLayer
suite.addTest(unittest.makeSuite(Test))
return suite
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
zope.app.form-4.0.2/src/zope/app/form/browser/tests/testconfigure.zcml 0000644 0001750 0001750 00000000741 11340453312 025405 0 ustar sidnei sidnei
zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_functional_i18n.py 0000644 0001750 0001750 00000004321 11340453312 026245 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Test form i18n
$Id: test_functional_i18n.py 107401 2009-12-30 22:56:20Z faassen $
"""
import re
import unittest
import doctest
from persistent import Persistent
from zope.testing import renormalizing
from zope.interface import Interface, implements
from zope.schema import TextLine, Text, Int, List
from zope.i18nmessageid import MessageFactory
from zope.app.testing.functional import FunctionalDocFileSuite
from zope.app.form.testing import AppFormLayer
_ = MessageFactory('formtest')
__docformat__ = "reStructuredText"
class IFieldContent(Interface):
title = TextLine(
title=_(u"Title"),
description=_(u"A short description of the event."),
default=u"",
required=True
)
description = Text(
title=_(u"Description"),
description=_(u"A long description of the event."),
default=u"",
required=False
)
somenumber = Int(
title=_(u"Some number"),
default=0,
required=False
)
somelist = List(
title=_(u"Some List"),
value_type=TextLine(title=_(u"Some item")),
default=[],
required=False
)
class FieldContent(Persistent):
implements(IFieldContent)
checker = renormalizing.RENormalizing([
(re.compile(r"HTTP/1\.1 200 .*"), "HTTP/1.1 200 OK"),
])
def test_suite():
i18n = FunctionalDocFileSuite('i18n.txt', package='zope.app.form.browser',
checker=checker)
i18n.layer = AppFormLayer
return unittest.TestSuite([
i18n,
])
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
zope.app.form-4.0.2/src/zope/app/form/browser/tests/__init__.py 0000644 0001750 0001750 00000000075 11340453312 023746 0 ustar sidnei sidnei #
# This file is necessary to make this directory a package.
zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_editview.py 0000644 0001750 0001750 00000014354 11340453312 025073 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Edit View Tests
$Id: test_editview.py 107371 2009-12-30 18:36:02Z faassen $
"""
import unittest
from zope.component.eventtesting import getEvents, clearEvents
from zope.component.testing import PlacelessSetup
from zope.interface import Interface, implements
from zope.location.interfaces import ILocation
from zope.publisher.browser import TestRequest
from zope.schema import TextLine, accessors
from zope.schema.interfaces import ITextLine
from zope.app.testing import ztapi
from zope.app.form.browser import TextWidget
from zope.app.form.browser.editview import EditView
from zope.app.form.browser.submit import Update
from zope.formlib.interfaces import IInputWidget
from zope.app.form.tests import utils
class I(Interface):
foo = TextLine(title=u"Foo")
bar = TextLine(title=u"Bar")
a = TextLine(title=u"A")
b = TextLine(title=u"B", min_length=0, required=False)
getbaz, setbaz = accessors(TextLine(title=u"Baz"))
class EV(EditView):
schema = I
object_factories = []
class C(object):
implements(I)
foo = u"c foo"
bar = u"c bar"
a = u"c a"
b = u"c b"
__Security_checker__ = utils.SchemaChecker(I)
_baz = u"c baz"
def getbaz(self): return self._baz
def setbaz(self, v): self._baz = v
class IFoo(Interface):
foo = TextLine(title=u"Foo")
class IBar(Interface):
bar = TextLine(title=u"Bar")
class Foo(object):
implements(IFoo)
__Security_checker__ = utils.SchemaChecker(IFoo)
foo = u'Foo foo'
class ConformFoo(object):
implements(IFoo)
foo = u'Foo foo'
def __conform__(self, interface):
if interface is IBar:
return OtherFooBarAdapter(self)
class FooBarAdapter(object):
implements(IBar, ILocation)
__used_for__ = IFoo
def __init__(self, context):
self.context = context
def getbar(self): return self.context.foo
def setbar(self, v): self.context.foo = v
bar = property(getbar, setbar)
__Security_checker__ = utils.SchemaChecker(IBar)
class OtherFooBarAdapter(FooBarAdapter):
pass
class BarV(EditView):
schema = IBar
object_factories = []
class Test(PlacelessSetup, unittest.TestCase):
def setUp(self):
super(Test, self).setUp()
ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)
ztapi.provideAdapter(IFoo, IBar, FooBarAdapter)
clearEvents()
def test_setPrefix_and_widgets(self):
v = EV(C(), TestRequest())
v.setPrefix("test")
self.assertEqual(
[w.name for w in v.widgets()],
['test.foo', 'test.bar', 'test.a', 'test.b', 'test.getbaz']
)
def test_empty_prefix(self):
v = EV(C(), TestRequest())
v.setPrefix("")
self.assertEqual(
[w.name for w in v.widgets()],
['foo', 'bar', 'a', 'b', 'getbaz']
)
def test_fail_wo_adapter(self):
c = Foo()
request = TestRequest()
self.assertRaises(TypeError, EV, c, request)
def test_update_no_update(self):
c = C()
request = TestRequest()
v = EV(c, request)
self.assertEqual(v.update(), '')
self.assertEqual(c.foo, u'c foo')
self.assertEqual(c.bar, u'c bar')
self.assertEqual(c.a , u'c a')
self.assertEqual(c.b , u'c b')
self.assertEqual(c.getbaz(), u'c baz')
request.form['field.foo'] = u'r foo'
request.form['field.bar'] = u'r bar'
request.form['field.a'] = u'r a'
request.form['field.b'] = u'r b'
request.form['field.getbaz'] = u'r baz'
self.assertEqual(v.update(), '')
self.assertEqual(c.foo, u'c foo')
self.assertEqual(c.bar, u'c bar')
self.assertEqual(c.a , u'c a')
self.assertEqual(c.b , u'c b')
self.assertEqual(c.getbaz(), u'c baz')
self.failIf(getEvents())
def test_update(self):
c = C()
request = TestRequest()
v = EV(c, request)
request.form[Update] = ''
request.form['field.foo'] = u'r foo'
request.form['field.bar'] = u'r bar'
request.form['field.getbaz'] = u'r baz'
request.form['field.a'] = u'c a'
message = v.update()
self.failUnless(message.startswith('Updated '), message)
self.assertEqual(c.foo, u'r foo')
self.assertEqual(c.bar, u'r bar')
self.assertEqual(c.a , u'c a')
self.assertEqual(c.b , u'c b') # missing from form - unchanged
self.assertEqual(c.getbaz(), u'r baz')
# Verify that calling update multiple times has no effect
c.__dict__.clear()
self.assertEqual(v.update(), message)
self.assertEqual(c.foo, u'c foo')
self.assertEqual(c.bar, u'c bar')
self.assertEqual(c.a , u'c a')
self.assertEqual(c.b , u'c b')
self.assertEqual(c.getbaz(), u'c baz')
def test_update_via_adapter(self):
f = Foo()
request = TestRequest()
v = BarV(f, request)
# check adapter
self.assertEqual(f.foo, u'Foo foo')
a = IBar(f)
self.assertEqual(a.bar, u'Foo foo')
# update
request.form[Update] = ''
request.form['field.bar'] = u'r bar'
message = v.update()
self.failUnless(message.startswith('Updated '), message)
self.assertEqual(a.bar, u'r bar')
# wrong update
self.failIf(getEvents())
def test_setUpWidget_via_conform_adapter(self):
f = ConformFoo()
request = TestRequest()
v = BarV(f, request)
def test_suite():
return unittest.makeSuite(Test)
if __name__=='__main__':
unittest.main(defaultTest='test_suite')
zope.app.form-4.0.2/src/zope/app/form/browser/tests/testeditform.pt 0000644 0001750 0001750 00000002053 11340453312 024711 0 ustar sidnei sidnei
Simple Edit Form
This is a Schema produced form
Errors:
:
zope.app.form-4.0.2/src/zope/app/form/browser/tests/testlabeltranslation.po 0000644 0001750 0001750 00000001143 11340453312 026430 0 ustar sidnei sidnei # SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR , YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2003-03-25 15:01-0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=us-ascii\n"
"Content-Transfer-Encoding: 8bit\n"
#: test_browserwidget.py:34
msgid "Foo Title"
msgstr "oofay itletay"
zope.app.form-4.0.2/src/zope/app/form/browser/tests/test_widgetdirective.py 0000644 0001750 0001750 00000005554 11340453312 026437 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Tests for the subdirective for the generated form pages.
$Id: test_widgetdirective.py 107371 2009-12-30 18:36:02Z faassen $
"""
import unittest
import zope.component
import zope.interface
import zope.configuration.xmlconfig
import zope.publisher.browser
import zope.schema
from zope.browser.interfaces import IAdding
import zope.app.form.browser.interfaces
import zope.formlib.interfaces
from zope.app.form.tests import utils
import zope.component.testing
__docformat__ = "reStructuredText"
class IContent(zope.interface.Interface):
field = zope.schema.TextLine(
title=u"Field",
description=u"Sample input field",
required=False,
)
class Content(object):
zope.interface.implements(IContent)
__Security_checker__ = utils.SchemaChecker(IContent)
__parent__ = None
__name__ = "sample-content"
field = None
class Adding(object):
zope.interface.implements(IAdding)
def add(self, content):
self.content = content
class WidgetDirectiveTestCase(zope.component.testing.PlacelessSetup,
unittest.TestCase):
def setUp(self):
super(WidgetDirectiveTestCase, self).setUp()
zope.configuration.xmlconfig.file("widgetDirectives.zcml",
zope.app.form.browser.tests)
def get_widget(self, name, context):
request = zope.publisher.browser.TestRequest()
view = zope.component.getMultiAdapter((context, request), name=name)
return view.field_widget
def test_addform_widget_without_class(self):
w = self.get_widget("add.html", Adding())
self.assert_(zope.formlib.interfaces.IInputWidget.providedBy(w))
self.assertEqual(w.extraAttr, "42")
def test_editform_widget_without_class(self):
w = self.get_widget("edit.html", Content())
self.assert_(zope.formlib.interfaces.IInputWidget.providedBy(w))
self.assertEqual(w.extraAttr, "84")
def test_subeditform_widget_without_class(self):
w = self.get_widget("subedit.html", Content())
self.assert_(zope.formlib.interfaces.IInputWidget.providedBy(w))
self.assertEqual(w.extraAttr, "168")
def test_suite():
return unittest.makeSuite(WidgetDirectiveTestCase)
zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/ 0000755 0001750 0001750 00000000000 11340453312 023255 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/de/ 0000755 0001750 0001750 00000000000 11340453341 023647 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/de/LC_MESSAGES/ 0000755 0001750 0001750 00000000000 11340453312 025432 5 ustar sidnei sidnei zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/de/LC_MESSAGES/formtest.po 0000644 0001750 0001750 00000002675 11340453312 027647 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
msgid ""
msgstr ""
"Project-Id-Version: Five form tests\n"
"POT-Creation-Date: \n"
"PO-Revision-Date: 2005-07-29 11:38+0100\n"
"Last-Translator: \n"
"Language-Team: Five Developers \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
msgid "Title"
msgstr "Titel"
msgid "A short description of the event."
msgstr "Eine kurze Beschreibung des Ereignisses."
msgid "Description"
msgstr "Beschreibung"
msgid "A long description of the event."
msgstr "Eine ausführliche Beschreibung des Ereignisses."
msgid "Some number"
msgstr "Irgendeine Zahl"
msgid "Some List"
msgstr "Irgendeine Liste"
msgid "Some item"
msgstr "Irgendeine Element"
msgid "Edit Field Content"
msgstr "Felderinhalt bearbeiten"
msgid "Add Field Content"
msgstr "Felderinhalt hinzufügen"
zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/de/LC_MESSAGES/formtest.mo 0000644 0001750 0001750 00000001534 11340453312 027635 0 ustar sidnei sidnei Þ•
l
¼ ð ñ ! 4 F R e o y … þ ‹ 0 Š ( » ä ý
" 3 F V
A long description of the event. A short description of the event. Add Field Content Description Edit Field Content Some List Some item Some number Title Project-Id-Version: Five form tests
POT-Creation-Date:
PO-Revision-Date: 2005-07-29 11:38+0100
Last-Translator:
Language-Team: Five Developers
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Eine ausführliche Beschreibung des Ereignisses. Eine kurze Beschreibung des Ereignisses. Felderinhalt hinzufügen Beschreibung Felderinhalt bearbeiten Irgendeine Liste Irgendeine Element Irgendeine Zahl Titel zope.app.form-4.0.2/src/zope/app/form/browser/tests/locales/formtest.pot 0000644 0001750 0001750 00000002336 11340453312 025650 0 ustar sidnei sidnei ##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
msgid ""
msgstr ""
"Project-Id-Version: Five form tests\n"
"POT-Creation-Date: \n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: Five Developers \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
msgid "Title"
msgstr ""
msgid "A short description of the event."
msgstr ""
msgid "Description"
msgstr ""
msgid "A long description of the event."
msgstr ""
msgid "Some number"
msgstr ""
msgid "Some List"
msgstr ""
msgid "Some item"
msgstr ""
msgid "Edit Field Content"
msgstr ""
msgid "Add Field Content"
msgstr ""
zope.app.form-4.0.2/src/zope/app/form/browser/tests/i18n.zcml 0000644 0001750 0001750 00000001013 11340453312 023274 0 ustar sidnei sidnei
zope.app.form-4.0.2/src/zope/app/form/browser/tests/widgetDirectives.zcml 0000644 0001750 0001750 00000002316 11340453312 026031 0 ustar sidnei sidnei
zope.app.form-4.0.2/src/zope/app/form/browser/tests/testlabeltranslation.mo 0000644 0001750 0001750 00000000613 11340453312 026426 0 ustar sidnei sidnei Þ• , <