Package: plone.directives.form
This package provides optional, Grok-like directives for configuring
forms, as defined by thez3c.formlibrary, using XML schemata as defined byplone.supermodeland/or using widget form layout as defined byplone.autoform. It depends onfive.grok, which in turn depends on the
various re-usable grokcore.* packages, but not Grok itself.ContentsInstallationSchemata loaded from XMLForm widget hintsValue adaptersValidatorsError messagesForm base classesTroubleshootingForms are not foundChangelog2.0.3 (2017-05-09)2.0.2 (2015-11-28)2.0.1 (2015-05-04)2.0 (2012-08-30)1.0 - 2011-05-201.0b7 - 2010-04-201.0b6 - 2009-10-081.0b5 - 2009-07-211.0b3 - 2009-07-121.0b2 - 2009-06-151.0b1 - 2009-04-17InstallationTo use this package you must first install it, either by depending on it
in your ownsetup.py(under theinstall_requireslist), or by adding
it directly to your buildout.This will pull in a number of dependencies. You probably want to pin those
down to known-good versions by using a known-good version set. See the
installation instructions offive.grokfor a starting point.You must also load the relevant configuration frommeta.zcmlandconfigure.zcml. For example, you could use statements like the following
in yourconfigure.zcml:<include package="plone.directives.form" file="meta.zcml" />
<include package="plone.directives.form" />or if you declare dependencies in setup.py using install_requires:<includeDependencies package="." />Schemata loaded from XMLplone.directives.formused to contain a directive for loading an XML-based
schema model into a Python interface.  This directive has moved toplone.supermodel, asplone.supermodel.model.load.Form widget hintsplone.directives.formused to contain a number of directives for generating
a form from a schema, using hints stored in tagged values on that schema to
control the form’s layout and field widgets. These directives have now moved
to other packages to avoid a dependency of Dexterity on grok.Thefieldsetandprimarydirectives are now inplone.supermodel.model.Theomitted,no_omit,mode,widget,order_before,order_after,read_permission, andwrite_permissiondirectives are
now inplone.autoform.directives.Value adaptersz3c.form has the concept of a “value adapter”, a component that can provide
a value for an attribute (usually of widgets and buttons) at runtime. This
package comes with some helpful decorators to register value adapters for
computed values. For example:from plone.directives import form
from zope import schema

class IMySchema(form.Schema):

    title = schema.TextLine(title=u"Title")

@form.default_value(field=IMySchema['title'])
def default_title(data):
    return data.context.suggested_titleThe decorator takes one or more discriminators. The available discriminators
fordefault_valueare:contextThe type of context (e.g. an interface)requestThe type of request (e.g. a layer marker interface). You can
use ‘layer’ as an alias for ‘request’, but note that the data passed
to the function will have a ‘request’ attribute only.viewThe type of form (e.g. a form instance or interface). You can
use ‘form’ as an alias for ‘view’, but note that the data passed to
the function will have ‘view’ attribute only.fieldThe field instance (or a field interface).widgetThe widget type (e.g. an interface).You must specify eitherfieldorwidget. The object passed to the
decorated function has an attribute for each discriminator.There are two more decorators:widget_labelProvide a dynamic label for a widget. Takes the same discriminators as thedefault_valuedecorator.button_label – Provide a dynamic label for a button. Takes parameterscontent (alias context), request (alias layer), form (alias view),
manager and button.Please note the rather unfortunate differences in naming between the button
descriptors (content vs. context, form vs. view) and the widget ones. The
descriptor will accept the same names, but the data object passed to the
function will only contain the names as defined in z3c.form, so be careful.ValidatorsBy default, z3c.form uses fields’ native validation, as implemented by theIField.validate()method, as well as field constraints (functions passed
as theconstraintparameter to fields) and schema invariants (using the@zope.interface.invariantdecorator in a schema interface). In addition,
you can define your own widget validators (for an individual field of the
form) and widget manager validators (which cover the entire form). This is
useful if you do not want to define a validator on the schema, e.g. because
the schema is also used elsewhere, or if you want to create a more generic
validator that is applied to any fields that match its discriminators.This package provides a grokked decorator which you can use to define a simple
widget validator, called@form.validator():from plone.directives import form
from zope import schema

class IMySchema(form.Schema):

    title = schema.TextLine(title=u"Title")

@form.validator(field=IMySchema['title'])
def validateTitle(value):
    if value == value.upper():
        raise schema.ValidationError(u"Please don't shout")The validator should return nothing if the field is valid, or raise anzope.schema.ValidationErrorexception with an error message.The@form.validator()decorator can take various keyword arguments that
determine when the validator is invoked. These are:contextThe type of context (e.g. an interface)requestThe type of request (e.g. a layer marker interface).viewThe type of form (e.g. a form instance or interface).fieldThe field instance (or a field interface).widgetThe widget type (e.g. an interface).Note that this validator function does not give access to the full context
of the standard validator, such as the field, widget, context or request.
If you need that, you can create a standard validator adapter, e.g. usinggrok.Adapter. See thez3c.formdocumentation for details.Also note that the standard field validator will be called before the custom
validator is invoked. If you need to override the validator wholesale, you
can again do so with a custom adapter.Error messagesWhen using custom validators, it is easy to supply a tailored error message.
However, the error messages that arise from the default field validation
mechanism (e.g. when a required field is omitted) are by necessity more
generic. Sometimes, it may be necessary to override these messages to make
them more user friendly.To customise an error message, you can use the@form.error_messagegrokked
decorator. For example:from plone.directives import form
from zope import schema

from zope.schema.interfaces import TooShort

class IMySchema(form.Schema):

    title = schema.TextLine(title=u"Title", min_length=2)

@form.error_message(error=TooShort, field=IMySchema['title'])
def titleTooShort(value):
    return u"The title '%s' is too short" % valueThe decorated function will be called when constructing an error message for
the given field. It should return a unicode string or translatable message.
The value passed is the value that failed validation.The@form.error_messagevalidator takes keyword arguments that determine
when the message is used. It is possible to register a generic error message
for a given type of error that applies to all fields, or, as shown above,
a message specific to an individual field and error. The latter is more
common. In general, you should be careful if you omit either or both of theerrorandfielddiscriminators.errorAn exception class that represents the error. All errors inherit fromzope.interface.Invalid, and most error also inherit fromzope.schema.interfaces.ValidationError. See below for a list of
common exception types.requestThe current request. Use this to tie the error to a specific browser
layer interface.widgetThe widget that was used. May be either a widget interface or a specific
widget class.fieldThe field that was used, normally given as a field instance obtained from
an interface, as illustrated above.formThe current form, either as a class or an interface. This is useful if
the same interface is used in more than one form, but you only want the
error to be shown in one form.contentThe content item that is acting as the context for the form. May be given
as either an interface or a class.None of these parameters is required, but you would normally supply at leasterror. In most cases, you should also supply thefield, as shown
above.The most common validation error exception types are defined inzope.schema, and can be imported fromzope.schema.interfaces:RequiredMissing, used when a required field is submitted without a valueWrongType, used when a field is passed a value of an invalid typeTooBigandTooSmall, used when a value is outside theminand/ormaxrange specified for ordered fields (e.g. numeric or date fields)TooLongandTooShort, used when a value is outside themin_lengthand/ormax_lengthrange specified for length-aware fields
(e.g. text or sequence fields)InvalidValue, used when a value is invalid, e.g. a non-ASCII character
passed to an ASCII fieldConstraintNotSatisfied, used when aconstraintmethod returnsFalseWrongContainedType, used if an object of an invalid type is added
to a sequence (i.e. the type does not conform to the field’svalue_type)NotUnique, used if a uniqueness constraint is violatedInvalidURI, used forURIfields if the value is not a valid URIInvalidId, used forIdfields if the value is not a valid idInvalidDottedName, used forDottedNamefields if the value is not
a valid dotted nameForm base classesIf you need to create your own forms, this package provides a number of
convenient base classes that will be grokked much like agrok.View.In Zope 2.10, the grokkers take care of wrapping the form in aplone.z3cformFormWrapper as well. In Zope 2.12 and later, there is no
wrapper by default. If you want one (e.g. if you are using a custom template
and you need it to work in both Zope 2.10 and 2.12), you can use theform.wrap()directive in the form class.The base classes can all be imported fromplone.directives.form, e.g:from five import grok
from plone.directives import form, button
from z3c.form import field

class MyForm(form.Form):
    grok.context(ISomeContext)
    grok.require('zope2.View')

    fields = field.Fields(IMyFormSchema)

    @button.buttonAndHandler(u'Submit')
    def handleApply(self, action):
        data, errors = self.extractData()
        ...The allowed directives are:grok.context(), to specify the context of form view. If not given, the
grokker will look for a module-level context, much like the standardgrok.View.grok.require(), to specify a permission. The default iszope2.Viewfor standard forms,cmf.ModifyPortalContentfor edit forms, andcmf.AddPortalContentfor add forms.grok.layer()to specify a browser layergrok.name()to set a different name. By default your form will be
available as view @@yourformclassnamelowercase, but you can usegrok.name()to set name explicitly.form.wrap()to wrap the form in a layout wrapper view. You can pass
an argument ofTrueorFalseto enable or disable wrapping. If no
argument is given, it defaults toTrue. If omitted, the global default
is used, which is to wrap in Zope 2.11 or earlier, and to not wrap in Zope
2.12 or laterMore complex example how to use Grok directives with a form:from plone.directives import form
from Products.CMFCore.interfaces import ISiteRoot

class CompanyCreationForm(form.SchemaForm):
    """ A sample form how to "create companies".

    """

    # Which plone.directives.form.Schema subclass is used to define
    # fields for this form (not shown on this example)
    schema = ICompanyCreationFormSchema

    # Permission required to view/submit the form
    grok.require("cmf.ManagePortal")

    # The form does not care about the context object
    # and  should not try to extract field value
    # defaults out of it
    ignoreContext = True

    # This form is available at the site root only
    grok.context(ISiteRoot)

    # The form will be available in Plone site root only
    # Use http://yourhost/@@create_company URL to access this form
    grok.name("create_company")Each of the form base classes has a “schema” equivalent, which can be
initialised with aschemaattribute instead of thefieldsattribute.
These forms useplone.autoform’sAutoExtensibleFormas a base class,
allowing schema hints as shown above to be processed:from plone.directives import form
from z3c.form import button

class MyForm(form.SchemaForm):
    grok.context(ISomeContext)
    grok.require('zope2.View')

    schema = IMySchema

    @button.buttonAndHandler(u'Submit')
    def handleApply(self, action):
        data, errors = self.extractData()
        ...Note that theschemacan be omitted if you are usingSchemaFormorSchemaEditFormand you have given an interface as the argument togrok.context(). In this case, the context interface will be used as the
default schema.The available form base classes are:FormA simple page form, basically a grokked version ofz3c.form.form.Form.SchemaFormA page form that usesplone.autoform. You must set theschemaclass
variable (or implement it as a property) to a schema interface form which
the form will be built. Form widget hints will be taken into account.AddFormA simple add form with “Add” and “Cancel” buttons. You must implement
thecreate()andadd()methods. See thez3c.formdocumentation
for more details.SchemaAddFormAn add form usingplone.autoform. Again, you must set theschemaclass variable.EditFormA simple edit form with “Save” and “Cancel” buttons. See thez3c.formdocumentation for more details.SchemaEditFormAn edit form usingplone.autoform. Again, you must set theschemaclass variable.DisplayFormA view with an automatically associated template (likegrok.View),
that is initialised with display widgets. Seeplone.autoform’sWidgetsViewfor more details.All of the grokked form base classes above support associating a custom
template with the form. This uses the same semantics asgrok.View. Seegrokcore.viewfor details, but briefly:If you want to completely customise rendering, you can override therender()method.If you want to use a page template to render a form calledMyFormin
the modulemy.package.forms, create a directory insidemy.packagecalledforms_templates(the prefix should match the module name),
and place a file there calledmyform.pt.If you do neither, the default form template will be used, as is the
standard behaviour in z3c.form.Note that the automatically associated form template can usegrok.Viewmethods, such asview.url()andview.redirect(), which are defined
in the grokked form base classes.Also note that you can use the view@@ploneform-macrosfromplone.app.z3cformif you want to use some of the standard form markup.
For example, thetitlelessformmacro will render the<form >element
and all fieldsets and fields:<metal:block use-macro="context/@@ploneform-macros/titlelessform" />TroubleshootingForms are not foundWhen you try to access your form on the site, you’ll get page not found (NotFound exception).Make sure that you typed your form name correctly and it matchesgrok.name()or lowercased class nameMake sure you have <include package=”plone.directives.form” file=”meta.zcml” />
or similar in configure.zcml of your add-on productChangelog2.0.3 (2017-05-09)Bug fixes:Remove unused import and added a missing import on example.
[bruno]Update setup.py to point to github repository.
[esteele]2.0.2 (2015-11-28)Fixes:Changed i18n_domain to “plone”.
[staeff]Removed unneeded i18n-attribute.
[staeff]2.0.1 (2015-05-04)pep8.
[maurits]Whitespaces cleanup.
[gforcada]2.0 (2012-08-30)Update to work with grokcore.view >= 2.2. This generally means that this
package is no longer compatible with Plone < 4.3.
[davisagli]Change i18n domain to plone.dexterity to reuse the translations. plone.dexterity
already has all the strings needed.
[gaudenz]Fixes documentation mistake of documentedform.wrapped()directive
which is in factform.wrap()[romanofski]A number of schema directives were moved to other packages and reimplemented
to not depend on grok.  TheSchemaclass and themodel,fieldset,
andprimarydirectives were moved toplone.supermodel.model. Theomitted,no_omit,mode,widget,order_before,order_after,read_permission, andwrite_permissiondirectives were
moved toplone.autoform.directives.For now the directives are still available under their old names in this
package, but they are deprecated and may be removed at some point.Some minor related changes:Tagged values are now stored on schemas as soon as they are defined, rather
than when the schemas are grokked. Additional actions required by the
directives, if any, are performed at the end of ZCML configuration.Due to a bug in zope.interface,plone.supermodel.model.Schemamust be
thefirstbase class of any schema to which the directives should apply.
Also, unfortunately it is no longer possible to give an error if the schema
directives are called on an interface that is not aSchema.[davisagli]1.0 - 2011-05-20No changes.1.0b7 - 2010-04-20Allow arbitrary extra parameters for the fieldset directive. This is useful
for extensions that want to tweak fieldset behaviour or rendering.
[wichert]Addno_omitdirective, so that fields that have been omitted can be
re-included again on for a more specific form interface.
[davisagli]Accept a form interface as an optional positional argument for themodeandomitteddirectives, and store it in the tagged values using the new
format expected by plone.autoform.
[davisagli]Add@form.error_message()decorator for registering custom error
messages for errors and/or fields.
[optilude]Add@form.validator()decorator to register a simple field validator.
See README.txt for details.
[optilude]Support unwrapped forms (in Zope 2.12). The default is to wrap in Zope <
2.12, and not to wrap in Zope >= 2.12. A newform.wrapped()directive
can be used to force wrapping or non-wrapping (by passingFalseas an
argument).
[optilude]Warn more forcefully when using form directives on interfaces not deriving
fromSchema, or using schema hints that refer to field names that cannot
be found.
[optilude]1.0b6 - 2009-10-08Add support for theprimary()directive, which is used to set the
primary field for marshalling. See theplone.rfc822for details.
[optilude]1.0b5 - 2009-07-21Updated to new five.grok release.
[optilude]1.0b3 - 2009-07-12Made adjustments for changes in plone.supermodel’s API.
[optilude]1.0b2 - 2009-06-15Make sure that we don’t lose the function when using the
@form.default_value() decorator and the other value decorators.
[optilude]1.0b1 - 2009-04-17Initial release