Plone技术资料

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 3629|回复: 0

z3c.form模块介绍(一、接口)

[复制链接]
发表于 2015-1-4 19:50:19 | 显示全部楼层 |阅读模式
了解python模块最好的办法是先看接口。
下面为z3c.form接口:
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2007 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Form and Widget Framework Interfaces
  15. """
  16. __docformat__ = "reStructuredText"
  17. import zope.i18nmessageid
  18. import zope.interface
  19. import zope.schema
  20. from zope.interface.common import mapping
  21. from zope.location.interfaces import ILocation

  22. MessageFactory = _ = zope.i18nmessageid.MessageFactory('z3c.form')

  23. INPUT_MODE = 'input'
  24. DISPLAY_MODE = 'display'
  25. HIDDEN_MODE = 'hidden'

  26. class NOT_CHANGED(object):
  27.     def __repr__(self):
  28.         return '<NOT_CHANGED>'
  29. NOT_CHANGED = NOT_CHANGED()

  30. class NO_VALUE(object):
  31.     def __repr__(self):
  32.         return '<NO_VALUE>'
  33. NO_VALUE = NO_VALUE()
  34. # BBB: the object was renamed to follow common naming style
  35. NOVALUE = NO_VALUE

  36. # ----[ Layer Declaration ]--------------------------------------------------

  37. class IFormLayer(zope.interface.Interface):
  38.     """A layer that contains all registrations of this package.

  39.     It is intended that someone can just use this layer as a base layer when
  40.     using this package.

  41.     Since version 2.4.2, this layer doesn't provide IBrowserRequst anymore.
  42.     This makes it possible to use the IFormLayer within z3c.jsonrpc without
  43.     to apply the IBrowserRequest into the jsonrpc request.
  44.     """


  45. # ----[ Generic Manager Interfaces ]-----------------------------------------

  46. class IManager(mapping.IEnumerableMapping):
  47.     """A manager of some kind of items.

  48.     *Important*: While managers are mappings, the order of the items is
  49.      assumed to be important! Effectively a manager is an ordered mapping.

  50.     In general, managers do not have to support a manipulation
  51.     API. Oftentimes, managers are populated during initialization or while
  52.     updating.
  53.     """

  54. class ISelectionManager(IManager):
  55.     """Managers that support item selection and management.

  56.     This manager allows one to more carefully specify the contained items.

  57.     *Important*: The API is chosen in a way, that the manager is still
  58.     immutable. All methods in this interface must return *new* instances of
  59.     the manager.
  60.     """

  61.     def __add__(other):
  62.         """Used for merge two managers."""

  63.     def select(*names):
  64.         """Return a modified instance with an ordered subset of items."""

  65.     def omit(*names):
  66.         """Return a modified instance omitting given items."""

  67.     def copy():
  68.         """Copy all items to a new instance and return it."""


  69. # ----[ Validators ]---------------------------------------------------------

  70. class IData(zope.interface.Interface):
  71.     """A proxy object for form data.

  72.     The object will make all keys within its data attribute available as
  73.     attributes. The schema that is represented by the data will be directly
  74.     provided by instances.
  75.     """

  76.     def __init__(schema, data, context):
  77.         """The data proxy is instantiated using the schema it represents, the
  78.         data fulfilling the schema and the context in which the data are
  79.         validated.
  80.         """

  81.     __context__ = zope.schema.Field(
  82.         title=_('Context'),
  83.         description=_('The context in which the data are validated.'),
  84.         required=True)

  85. class IValidator(zope.interface.Interface):
  86.     """A validator for a particular value."""

  87.     def validate(value, force=False):
  88.         """Validate the value.

  89.         If successful, return ``None``. Otherwise raise an ``Invalid`` error.
  90.         """

  91. class IManagerValidator(zope.interface.Interface):
  92.     """A validator that validates a set of data."""

  93.     def validate(data):
  94.         """Validate a dictionary of data.

  95.         This method is only responsible of validating relationships between
  96.         the values in the data. It can be assumed that all values have been
  97.         validated in isolation before.

  98.         The return value of this method is a tuple of errors that occurred
  99.         during the validation process.
  100.         """

  101.     def validateObject(obj):
  102.         """Validate an object.

  103.         The same semantics as in ``validate()`` apply, except that the values
  104.         are retrieved from the object and not the data dictionary.
  105.         """


  106. # ----[ Errors ]--------------------------------------------------------------

  107. class IErrorViewSnippet(zope.interface.Interface):
  108.     """A view providing a view for an error"""

  109.     widget = zope.schema.Field(
  110.         title = _("Widget"),
  111.         description = _("The widget that the view is on"),
  112.         required = True)

  113.     error = zope.schema.Field(
  114.         title=_('Error'),
  115.         description=_('Error the view is for.'),
  116.         required=True)

  117.     def update():
  118.         """Update view."""

  119.     def render():
  120.         """Render view."""

  121. class IMultipleErrors(zope.interface.Interface):
  122.     """An error that contains many errors"""

  123.     errors = zope.interface.Attribute("List of errors")

  124. # ----[ Fields ]--------------------------------------------------------------

  125. class IField(zope.interface.Interface):
  126.     """Field wrapping a schema field used in the form."""

  127.     __name__ = zope.schema.TextLine(
  128.         title=_('Title'),
  129.         description=_('The name of the field within the form.'),
  130.         required=True)

  131.     field = zope.schema.Field(
  132.         title=_('Schema Field'),
  133.         description=_('The schema field that is to be rendered.'),
  134.         required=True)

  135.     prefix = zope.schema.Field(
  136.         title=_('Prefix'),
  137.         description=_('The prefix of the field used to avoid name clashes.'),
  138.         required=True)

  139.     mode = zope.schema.Field(
  140.         title=_('Mode'),
  141.         description=_('The mode in which to render the widget for the field.'),
  142.         required=True)

  143.     interface = zope.schema.Field(
  144.         title=_('Interface'),
  145.         description=_('The interface from which the field is coming.'),
  146.         required=True)

  147.     ignoreContext = zope.schema.Bool(
  148.         title=_('Ignore Context'),
  149.         description=_('A flag, when set, forces the widget not to look at '
  150.                       'the context for a value.'),
  151.         required=False)

  152.     widgetFactory = zope.schema.Field(
  153.         title=_('Widget Factory'),
  154.         description=_('The widget factory.'),
  155.         required=False,
  156.         default=None,
  157.         missing_value=None)

  158.     showDefault = zope.schema.Bool(
  159.         title=_('Show default value'),
  160.         description=_('A flag, when set, makes the widget to display'
  161.                       'field|adapter provided default values.'),
  162.         default=True,
  163.         required=False)


  164. class IFields(ISelectionManager):
  165.     """IField manager."""

  166.     def select(prefix=None, interface=None, *names):
  167.         """Return a modified instance with an ordered subset of items.

  168.         This extension to the ``ISelectionManager`` allows for handling cases
  169.         with name-conflicts better by separating field selection and prefix
  170.         specification.
  171.         """

  172.     def omit(prefix=None, interface=None, *names):
  173.         """Return a modified instance omitting given items.

  174.         This extension to the ``ISelectionManager`` allows for handling cases
  175.         with name-conflicts better by separating field selection and prefix
  176.         specification.
  177.         """

  178. class IContentProviders(IManager):
  179.     """
  180.     A content provider manager
  181.     """

  182. # ----[ Data Managers ]------------------------------------------------------

  183. class IDataManager(zope.interface.Interface):
  184.     """Data manager."""

  185.     def get():
  186.         """Get the value.

  187.         If no value can be found, raise an error
  188.         """

  189.     def query(default=NO_VALUE):
  190.         """Get the value.

  191.         If no value can be found, return the default value.
  192.         If access is forbidden, raise an error.
  193.         """

  194.     def set(value):
  195.         """Set the value"""

  196.     def canAccess():
  197.         """Can the value be accessed."""

  198.     def canWrite():
  199.         """Can the data manager write a value."""


  200. # ----[ Data Converters ]----------------------------------------------------

  201. class IDataConverter(zope.interface.Interface):
  202.     """A data converter from field to widget values and vice versa."""

  203.     def toWidgetValue(value):
  204.         """Convert the field value to a widget output value.

  205.         If conversion fails or is not possible, a ``ValueError`` *must* be
  206.         raised. However, this method should effectively never fail, because
  207.         incoming value is well-defined.
  208.         """

  209.     def toFieldValue(value):
  210.         """Convert an input value to a field/system internal value.

  211.         This methods *must* also validate the converted value against the
  212.         field.

  213.         If the conversion fails, a ``ValueError`` *must* be raised. If
  214.         the validation fails, a ``ValidationError`` *must* be raised.
  215.         """


  216. # value interfaces
  217. class IValue(zope.interface.Interface):
  218.     """A value."""

  219.     def get():
  220.         """Returns the value."""


  221. # term interfaces
  222. class ITerms(zope.interface.Interface):
  223.     """ """

  224.     context = zope.schema.Field()
  225.     request = zope.schema.Field()
  226.     form = zope.schema.Field()
  227.     field = zope.schema.Field()
  228.     widget = zope.schema.Field()

  229.     def getTerm(value):
  230.         """Return an ITitledTokenizedTerm object for the given value

  231.         LookupError is raised if the value isn't in the source
  232.         """

  233.     def getTermByToken(token):
  234.         """Return an ITokenizedTerm for the passed-in token.

  235.         If `token` is not represented in the vocabulary, `LookupError`
  236.         is raised.
  237.         """

  238.     def getValue(token):
  239.         """Return a value for a given identifier token

  240.         LookupError is raised if there isn't a value in the source.
  241.         """

  242.     def __iter__():
  243.         """Iterate over terms."""

  244.     def __len__():
  245.         """Return number of terms."""

  246.     def __contains__(value):
  247.         """Check wether terms containes the ``value``."""


  248. class IBoolTerms(ITerms):
  249.     """A specialization that handles boolean choices."""

  250.     trueLabel = zope.schema.TextLine(
  251.         title=_('True-value Label'),
  252.         description=_('The label for a true value of the Bool field.'),
  253.         required=True)

  254.     falseLabel = zope.schema.TextLine(
  255.         title=_('False-value Label'),
  256.         description=_('The label for a false value of the Bool field.'),
  257.         required=False)


  258. # ----[ Object factory ]-----------------------------------------------------

  259. class IObjectFactory(zope.interface.Interface):
  260.     """Factory that will instantiate our objects for ObjectWidget.
  261.     It could also pre-populate properties as it gets the values extracted
  262.     from the form passed in ``value``.
  263.     """

  264.     def __call__(value):
  265.         """Return a default object created to be populated.
  266.         """


  267. # ----[ Subform factory ]-----------------------------------------------------

  268. class ISubformFactory(zope.interface.Interface):
  269.     """Factory that will instantiate our subforms for ObjectWidget.
  270.     """

  271.     def __call__():
  272.         """Return a default object created to be populated.
  273.         """

  274. # ----[ Widget layout template ]----------------------------------------------

  275. class IWidgetLayoutTemplate(zope.interface.Interface):
  276.     """Widget layout template marker used for render the widget layout.

  277.     It is important that we don't inherit this template from IPageTemplate.
  278.     otherwise we will get into trouble since we lookup an IPageTemplate
  279.     in the widget/render method.

  280.     """

  281. # ----[ Widgets ]------------------------------------------------------------

  282. class IWidget(ILocation):
  283.     """A widget within a form"""

  284.     name = zope.schema.ASCIILine(
  285.         title=_('Name'),
  286.         description=_('The name the widget is known under.'),
  287.         required=True)

  288.     label = zope.schema.TextLine(
  289.         title=_('Label'),
  290.         description=_('''
  291.         The widget label.

  292.         Label may be translated for the request.

  293.         The attribute may be implemented as either a read-write or read-only
  294.         property, depending on the requirements for a specific implementation.
  295.         '''),
  296.         required=True)

  297.     mode = zope.schema.ASCIILine(
  298.         title=_('Mode'),
  299.         description=_('A widget mode.'),
  300.         default=INPUT_MODE,
  301.         required=True)

  302.     required = zope.schema.Bool(
  303.         title=_('Required'),
  304.         description=_('If true the widget should be displayed as required '
  305.                       'input.'),
  306.         default=False,
  307.         required=True)

  308.     error = zope.schema.Field(
  309.         title=_('Error'),
  310.         description=_('If an error occurred during any step, the error view '
  311.                       'stored here.'),
  312.         required=False)

  313.     value = zope.schema.Field(
  314.         title=_('Value'),
  315.         description=_('The value that the widget represents.'),
  316.         required=False)

  317.     template = zope.interface.Attribute('''The widget template''')
  318.     layout = zope.interface.Attribute('''The widget layout template''')

  319.     ignoreRequest = zope.schema.Bool(
  320.         title=_('Ignore Request'),
  321.         description=_('A flag, when set, forces the widget not to look at '
  322.                       'the request for a value.'),
  323.         default=False,
  324.         required=False)

  325.     # ugly thing to remove setErrors parameter from extract
  326.     setErrors = zope.schema.Bool(
  327.         title=_('Set errors'),
  328.         description=_('A flag, when set, the widget sets error messages '
  329.                       'on calling extract().'),
  330.         default=True,
  331.         required=False)

  332.     # a bit different from ignoreRequiredOnExtract, because we record
  333.     # here the fact, but for IValidator, because the check happens there
  334.     ignoreRequiredOnValidation = zope.schema.Bool(
  335.         title=_('Ignore Required validation'),
  336.         description=_("If set then required fields will pass validation "
  337.                       "regardless whether they're filled in or not"),
  338.         default=False,
  339.         required=True)

  340.     showDefault = zope.schema.Bool(
  341.         title=_('Show default value'),
  342.         description=_('A flag, when set, makes the widget to display'
  343.                       'field|adapter provided default values.'),
  344.         default=True,
  345.         required=False)

  346.     def extract(default=NO_VALUE):
  347.         """Extract the string value(s) of the widget from the form.

  348.         The return value may be any Python construct, but is typically a
  349.         simple string, sequence of strings or a dictionary.

  350.         The value *must not* be converted into a native format.

  351.         If an error occurs during the extraction, the default value should be
  352.         returned. Since this should never happen, if the widget is properly
  353.         designed and used, it is okay to NOT raise an error here, since we do
  354.         not want to crash the system during an inproper request.

  355.         If there is no value to extract, the default is to be returned.
  356.         """

  357.     def update():
  358.         """Setup all of the widget information used for displaying."""

  359.     def render():
  360.         """Render the plain widget without additional layout"""

  361.     def __call__():
  362.         """Render a layout template which is calling widget/render"""


  363. class ISequenceWidget(IWidget):
  364.     """Term based sequence widget base.

  365.     The sequence widget is used for select items from a sequence. Don't get
  366.     confused, this widget does support to choose one or more values from a
  367.     sequence. The word sequence is not used for the schema field, it's used
  368.     for the values where this widget can choose from.

  369.     This widget base class is used for build single or sequence values based
  370.     on a sequence which is in most use case a collection. e.g.
  371.     IList of IChoice for sequence values or IChoice for single values.

  372.     See also the MultiWidget for build sequence values based on none collection
  373.     based values. e.g. IList of ITextLine
  374.     """

  375.     noValueToken = zope.schema.ASCIILine(
  376.         title=_('NO_VALUE Token'),
  377.         description=_('The token to be used, if no value has been selected.'))

  378.     terms = zope.schema.Object(
  379.         title=_('Terms'),
  380.         description=_('A component that provides the options for selection.'),
  381.         schema=ITerms)

  382.     def updateTerms():
  383.         """Update the widget's ``terms`` attribute and return the terms.

  384.         This method can be used by external components to get the terms
  385.         without having to worry whether they are already created or not.
  386.         """


  387. class IMultiWidget(IWidget):
  388.     """None Term based sequence widget base.

  389.     The multi widget is used for ITuple, IList or IDict if no other widget is defined.

  390.     Some IList or ITuple are using another specialized widget if they can
  391.     choose from a collection. e.g. a IList of IChoice. The base class of such
  392.     widget is the ISequenceWidget.

  393.     This widget can handle none collection based sequences and offers add or
  394.     remove values to or from the sequence. Each sequence value get rendered by
  395.     it's own relevant widget. e.g. IList of ITextLine or ITuple of IInt
  396.     """


  397. class ISelectWidget(ISequenceWidget):
  398.     """Select widget with ITerms option."""

  399.     prompt = zope.schema.Bool(
  400.         title=_('Prompt'),
  401.         description=_('A flag, when set, enables a choice explicitely '
  402.                       'requesting the user to choose a value.'),
  403.         default=False)

  404.     items = zope.schema.Tuple(
  405.         title=_('Items'),
  406.         description=_('A collection of dictionaries containing all pieces of '
  407.                       'information for rendering. The following keys must '
  408.                       'be in each dictionary: id, value, content, selected'))

  409.     noValueMessage = zope.schema.Text(
  410.         title=_('No-Value Message'),
  411.         description=_('A human-readable text that is displayed to refer the '
  412.                       'missing value.'))

  413.     promptMessage = zope.schema.Text(
  414.         title=_('Prompt Message'),
  415.         description=_('A human-readable text that is displayed to refer the '
  416.                       'missing value.'))

  417. class IOrderedSelectWidget(ISequenceWidget):
  418.     """Ordered Select widget with ITerms option."""

  419. class ICheckBoxWidget(ISequenceWidget):
  420.     """Checbox widget."""

  421. class ISingleCheckBoxWidget(ICheckBoxWidget):
  422.     """Single Checbox widget."""

  423. class IRadioWidget(ISequenceWidget):
  424.     """Radio widget."""

  425.     def renderForValue(value):
  426.         """Render a single radio button element for a given value.

  427.         Here the word ``value`` is used in the HTML sense, in other
  428.         words it is a term token.
  429.         """

  430. class ISubmitWidget(IWidget):
  431.     """Submit widget."""

  432. class IImageWidget(IWidget):
  433.     """Submit widget."""

  434. class IButtonWidget(IWidget):
  435.     """Button widget."""

  436. class ITextAreaWidget(IWidget):
  437.     """Text widget."""

  438. class ITextLinesWidget(IWidget):
  439.     """Text lines widget."""

  440. class ITextWidget(IWidget):
  441.     """Text widget."""

  442. class IFileWidget(ITextWidget):
  443.     """File widget."""

  444. class IPasswordWidget(ITextWidget):
  445.     """Password widget."""

  446. class IObjectWidget(IWidget):
  447.     """Object widget."""

  448. class IWidgets(IManager):
  449.     """A widget manager"""

  450.     prefix = zope.schema.ASCIILine(
  451.         title=_('Prefix'),
  452.         description=_('The prefix of the widgets.'),
  453.         default='widgets.',
  454.         required=True)

  455.     mode = zope.schema.ASCIILine(
  456.         title=_('Prefix'),
  457.         description=_('The prefix of the widgets.'),
  458.         default=INPUT_MODE,
  459.         required=True)

  460.     errors = zope.schema.Field(
  461.         title=_('Errors'),
  462.         description=_('The collection of errors that occured during '
  463.                       'validation.'),
  464.         default=(),
  465.         required=True)

  466.     ignoreContext = zope.schema.Bool(
  467.         title=_('Ignore Context'),
  468.         description=_('If set the context is ignored to retrieve a value.'),
  469.         default=False,
  470.         required=True)

  471.     ignoreRequest = zope.schema.Bool(
  472.         title=_('Ignore Request'),
  473.         description=_('If set the request is ignored to retrieve a value.'),
  474.         default=False,
  475.         required=True)

  476.     ignoreReadonly = zope.schema.Bool(
  477.         title=_('Ignore Readonly'),
  478.         description=_('If set then readonly fields will also be shown.'),
  479.         default=False,
  480.         required=True)

  481.     ignoreRequiredOnExtract = zope.schema.Bool(
  482.         title=_('Ignore Required validation on extract'),
  483.         description=_("If set then required fields will pass validation "
  484.                       "on extract regardless whether they're filled in or not"),
  485.         default=False,
  486.         required=True)

  487.     hasRequiredFields = zope.schema.Bool(
  488.         title=_('Has required fields'),
  489.         description=_('A flag set when at least one field is marked as '
  490.                       'required'),
  491.         default=False,
  492.         required=False)

  493.     #ugly thing to remove setErrors parameter from extract
  494.     setErrors = zope.schema.Bool(
  495.         title=_('Set errors'),
  496.         description=_('A flag, when set, the contained widgets set error '
  497.                       'messages on calling extract().'),
  498.         default=True,
  499.         required=False)

  500.     def update():
  501.         """Setup widgets."""

  502.     def extract():
  503.         """Extract the values from the widgets and validate them.
  504.         """


  505. class IFieldWidget(zope.interface.Interface):
  506.     """Offers a field attribute.

  507.     For advanced uses the widget will make decisions based on the field
  508.     it is rendered for.
  509.     """

  510.     field = zope.schema.Field(
  511.         title=_('Field'),
  512.         description=_('The schema field which the widget is representing.'),
  513.         required=True)

  514. # ----[ Actions ]------------------------------------------------------------

  515. class ActionExecutionError(Exception):
  516.     """An error that occurs during the execution of an action handler."""

  517.     def __init__(self, error):
  518.         self.error = error

  519.     def __repr__(self):
  520.         return '<%s wrapping %r>' %(self.__class__.__name__, self.error)


  521. class WidgetActionExecutionError(ActionExecutionError):
  522.     """An action execution error that occurred due to a widget value being
  523.     incorrect."""

  524.     def __init__(self, widgetName, error):
  525.         ActionExecutionError.__init__(self, error)
  526.         self.widgetName = widgetName


  527. class IAction(zope.interface.Interface):
  528.     """Action"""

  529.     __name__ = zope.schema.TextLine(
  530.         title=_('Name'),
  531.         description=_('The object name.'),
  532.         required=False,
  533.         default=None)

  534.     title = zope.schema.TextLine(
  535.         title=_('Title'),
  536.         description=_('The action title.'),
  537.         required=True)

  538.     def isExecuted():
  539.         """Determine whether the action has been executed."""


  540. class IActionHandler(zope.interface.Interface):
  541.     """Action handler."""


  542. class IActionEvent(zope.interface.Interface):
  543.     """An event specific for an action."""

  544.     action = zope.schema.Object(
  545.         title=_('Action'),
  546.         description=_('The action for which the event is created.'),
  547.         schema=IAction,
  548.         required=True)


  549. class IActionErrorEvent(IActionEvent):
  550.     """An action event that is created when an error occurred."""

  551.     error = zope.schema.Field(
  552.         title=_('Error'),
  553.         description=_('The error that occurred during the action.'),
  554.         required=True)


  555. class IActions(IManager):
  556.     """A action manager"""

  557.     executedActions = zope.interface.Attribute(
  558.         '''An iterable of all executed actions (usually just one).''')

  559.     def update():
  560.         """Setup actions."""

  561.     def execute():
  562.         """Exceute actions.

  563.         If an action execution error is raised, the system is notified using
  564.         the action occurred error; on the other hand, if successful, the
  565.         action successfull event is sent to the system.
  566.         """


  567. class IButton(zope.schema.interfaces.IField):
  568.     """A button in a form."""

  569.     accessKey = zope.schema.TextLine(
  570.         title=_('Access Key'),
  571.         description=_('The key when pressed causes the button to be pressed.'),
  572.         min_length=1,
  573.         max_length=1,
  574.         required=False)

  575.     actionFactory = zope.schema.Field(
  576.         title=_('Action Factory'),
  577.         description=_('The action factory.'),
  578.         required=False,
  579.         default=None,
  580.         missing_value=None)


  581. class IImageButton(IButton):
  582.     """An image button in a form."""

  583.     image = zope.schema.TextLine(
  584.         title=_('Image Path'),
  585.         description=_('A relative image path to the root of the resources.'),
  586.         required=True)


  587. class IButtons(ISelectionManager):
  588.     """Button manager."""


  589. class IButtonAction(IAction, IWidget, IFieldWidget):
  590.     """Button action."""


  591. class IButtonHandlers(zope.interface.Interface):
  592.     """A collection of handlers for buttons."""

  593.     def addHandler(button, handler):
  594.         """Add a new handler for a button."""

  595.     def getHandler(button):
  596.         """Get the handler for the button."""

  597.     def copy():
  598.         """Copy this object and return the copy."""

  599.     def __add__(other):
  600.         """Add another handlers object.

  601.         During the process a copy of the current handlers object should be
  602.         created and the other one is added to the copy. The return value is
  603.         the copy.
  604.         """


  605. class IButtonHandler(zope.interface.Interface):
  606.     """A handler managed by the button handlers."""

  607.     def __call__(form, action):
  608.         """Execute the handler."""


  609. # ----[ Forms ]--------------------------------------------------------------

  610. class IHandlerForm(zope.interface.Interface):
  611.     """A form that stores the handlers locally."""

  612.     handlers = zope.schema.Object(
  613.         title=_('Handlers'),
  614.         description=_('A list of action handlers defined on the form.'),
  615.         schema=IButtonHandlers,
  616.         required=True)


  617. class IActionForm(zope.interface.Interface):
  618.     """A form that stores executable actions"""

  619.     actions = zope.schema.Object(
  620.         title=_('Actions'),
  621.         description=_('A list of actions defined on the form'),
  622.         schema=IActions,
  623.         required=True)

  624.     refreshActions = zope.schema.Bool(
  625.         title=_('Refresh actions'),
  626.         description=_('A flag, when set, causes form actions to be '
  627.                       'updated again after their execution.'),
  628.         default=False,
  629.         required=True)


  630. class IContextAware(zope.interface.Interface):
  631.     """Offers a context attribute.

  632.     For advanced uses, the widget will make decisions based on the context
  633.     it is rendered in.
  634.     """

  635.     context = zope.schema.Field(
  636.         title=_('Context'),
  637.         description=_('The context in which the widget is displayed.'),
  638.         required=True)

  639.     ignoreContext = zope.schema.Bool(
  640.         title=_('Ignore Context'),
  641.         description=_('A flag, when set, forces the widget not to look at '
  642.                       'the context for a value.'),
  643.         default=False,
  644.         required=False)


  645. class IFormAware(zope.interface.Interface):
  646.     """Offers a form attribute.

  647.     For advanced uses the widget will make decisions based on the form
  648.     it is rendered in.
  649.     """

  650.     form = zope.schema.Field()


  651. class IForm(zope.interface.Interface):
  652.     """Form"""

  653.     mode = zope.schema.Field(
  654.         title=_('Mode'),
  655.         description=_('The mode in which to render the widgets.'),
  656.         required=True)

  657.     ignoreContext = zope.schema.Bool(
  658.         title=_('Ignore Context'),
  659.         description=_('If set the context is ignored to retrieve a value.'),
  660.         default=False,
  661.         required=True)

  662.     ignoreRequest = zope.schema.Bool(
  663.         title=_('Ignore Request'),
  664.         description=_('If set the request is ignored to retrieve a value.'),
  665.         default=False,
  666.         required=True)

  667.     ignoreReadonly = zope.schema.Bool(
  668.         title=_('Ignore Readonly'),
  669.         description=_('If set then readonly fields will also be shown.'),
  670.         default=False,
  671.         required=True)

  672.     ignoreRequiredOnExtract = zope.schema.Bool(
  673.         title=_('Ignore Required validation on extract'),
  674.         description=_("If set then required fields will pass validation "
  675.                       "on extract regardless whether they're filled in or not"),
  676.         default=False,
  677.         required=True)

  678.     widgets = zope.schema.Object(
  679.         title=_('Widgets'),
  680.         description=_('A widget manager containing the widgets to be used in '
  681.                       'the form.'),
  682.         schema=IWidgets)

  683.     label = zope.schema.TextLine(
  684.         title=_('Label'),
  685.         description=_('A human readable text describing the form that can be '
  686.                       'used in the UI.'),
  687.         required=False)

  688.     labelRequired = zope.schema.TextLine(
  689.         title=_('Label required'),
  690.         description=_('A human readable text describing the form that can be '
  691.                       'used in the UI for rendering a required info legend.'),
  692.         required=False)

  693.     prefix = zope.schema.ASCIILine(
  694.         title=_('Prefix'),
  695.         description=_('The prefix of the form used to uniquely identify it.'),
  696.         default='form.')

  697.     status = zope.schema.Text(
  698.         title=_('Status'),
  699.         description=_('The status message of the form.'),
  700.         default=None,
  701.         required=False)

  702.     def getContent():
  703.         '''Return the content to be displayed and/or edited.'''

  704.     def updateWidgets(prefix=None):
  705.         '''Update the widgets for the form.

  706.         This method is commonly called from the ``update()`` method and is
  707.         mainly meant to be a hook for subclasses.

  708.         Note that you can pass an argument for ``prefix`` to override
  709.         the default value of ``"widgets."``.
  710.         '''

  711.     def extractData(setErrors=True):
  712.         '''Extract the data of the form.

  713.         setErrors: needs to be passed to extract() and to sub-widgets'''

  714.     def update():
  715.         '''Update the form.'''

  716.     def render():
  717.         '''Render the form.'''

  718. class ISubForm(IForm):
  719.     """A subform."""


  720. class IDisplayForm(IForm):
  721.     """Mark a form as display form, used for templates."""


  722. class IInputForm(zope.interface.Interface):
  723.     """A form that is meant to process the input of the form controls."""

  724.     action = zope.schema.URI(
  725.         title=_('Action'),
  726.         description=_('The action defines the URI to which the form data are '
  727.                       'sent.'),
  728.         required=True)

  729.     name = zope.schema.TextLine(
  730.         title=_('Name'),
  731.         description=_('The name of the form used to identify it.'),
  732.         required=False)

  733.     id = zope.schema.TextLine(
  734.         title=_('Id'),
  735.         description=_('The id of the form used to identify it.'),
  736.         required=False)

  737.     method = zope.schema.Choice(
  738.         title=_('Method'),
  739.         description=_('The HTTP method used to submit the form.'),
  740.         values=('get', 'post'),
  741.         default='post',
  742.         required=False)

  743.     enctype = zope.schema.ASCIILine(
  744.         title=_('Encoding Type'),
  745.         description=_('The data encoding used to submit the data safely.'),
  746.         default='multipart/form-data',
  747.         required=False)

  748.     acceptCharset = zope.schema.ASCIILine(
  749.         title=_('Accepted Character Sets'),
  750.         description=_('This is a list of character sets the server accepts. '
  751.                       'By default this is unknown.'),
  752.         required=False)

  753.     accept = zope.schema.ASCIILine(
  754.         title=_('Accepted Content Types'),
  755.         description=_('This is a list of content types the server can '
  756.                       'safely handle.'),
  757.         required=False)


  758. class IAddForm(IForm):
  759.     """A form to create and add a new component."""

  760.     def create(data):
  761.         """Create the new object using the given data.

  762.         Returns the newly created object.
  763.         """

  764.     def add(object):
  765.         """Add the object somewhere."""

  766.     def createAndAdd(data):
  767.         """Call create and add.

  768.         This method can be used for keep all attributes internal during create
  769.         and add calls. On sucess we return the new created and added object.
  770.         If something fails, we return None. The default handleAdd method will
  771.         only set the _finishedAdd marker on sucess.
  772.         """


  773. class IEditForm(IForm):
  774.     """A form to edit data of a component."""

  775.     def applyChanges(data):
  776.         """Apply the changes to the content component."""


  777. class IFieldsForm(IForm):
  778.     """A form that is based upon defined fields."""

  779.     fields = zope.schema.Object(
  780.         title=_('Fields'),
  781.         description=_('A field manager describing the fields to be used for '
  782.                       'the form.'),
  783.         schema=IFields)

  784. class IFieldsAndContentProvidersForm(IForm):
  785.     """A form that is based upon defined fields and content providers"""

  786.     contentProviders = zope.schema.Object(
  787.         title=_('Content providers'),
  788.         description=_('A manager describing the content providers to be used for '
  789.                       'the form.'),
  790.         schema=IContentProviders)

  791. class IButtonForm(IForm):
  792.     """A form that is based upon defined buttons."""

  793.     buttons = zope.schema.Object(
  794.         title=_('Buttons'),
  795.         description=_('A button manager describing the buttons to be used for '
  796.                       'the form.'),
  797.         schema=IButtons)

  798. class IGroup(IForm):
  799.     """A group of fields/widgets within a form."""

  800. class IGroupForm(IForm):
  801.     """A form that supports groups."""

  802.     groups = zope.schema.Tuple(
  803.         title=u'Groups',
  804.         description=(u'Initially a collection of group classes, which are '
  805.                      u'converted to group instances when the form is '
  806.                      u'updated.'))


  807. # ----[ Events ]--------------------------------------------------------------


  808. class IWidgetEvent(zope.interface.Interface):
  809.     """A simple widget event."""

  810.     widget = zope.schema.Object(
  811.         title=_('Widget'),
  812.         description=_('The widget for which the event was created.'),
  813.         schema=IWidget)


  814. class IAfterWidgetUpdateEvent(IWidgetEvent):
  815.     """An event sent out after the widget was updated."""


  816. class IDataExtractedEvent(zope.interface.Interface):
  817.     """Event sent after data and errors are extracted from widgets.
  818.     """
  819.     data = zope.interface.Attribute(
  820.         "Extracted form data. Usually, the widgets extract field names from "
  821.         "the request and return a dictionary of field names and field values."
  822.     )
  823.     errors = zope.interface.Attribute(
  824.         "Tuple of errors providing IErrorViewSnippet."
  825.     )
  826.     form = zope.interface.Attribute("Form instance.")
复制代码



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|手机版|Plone技术资料 ( 湘ICP备14006519号-1 )

GMT+8, 2019-11-18 09:03 , Processed in 1.648147 second(s), 16 queries , Gzip On.

Powered by Plone! X3.4

© 2001-2019 Plone.org.

快速回复 返回顶部 返回列表