code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
============== Data Converter ============== The data converter is the component that converts an internal data value as described by a field to an external value as required by a widget and vice versa. The goal of the converter is to avoid field and widget proliferation solely to handle different types of values. The purpose of fields is to describe internal data types and structures and that of widgets to provide one particular mean of input. The only two discriminators for the converter are the field and the widget. Let's look at the ``Int`` field to ``TextWidget`` converter as an example: >>> import zope.schema >>> age = zope.schema.Int( ... __name__='age', ... title='Age', ... min=0) >>> from z3c.form.testing import TestRequest >>> from z3c.form import widget >>> text = widget.Widget(TestRequest()) >>> from z3c.form import converter >>> conv = converter.FieldDataConverter(age, text) The field data converter is a generic data converter that can be used for all fields that implement ``IFromUnicode``. If, for example, a ``Date`` field -- which does not provide ``IFromUnicode`` -- is passed in, then a type error is raised: >>> converter.FieldDataConverter(zope.schema.Date(), text) Traceback (most recent call last): ... TypeError: Field of type ``Date`` must provide ``IFromUnicode``. A named field will tell it's name: >>> converter.FieldDataConverter(zope.schema.Date(__name__="foobar"), text) Traceback (most recent call last): ... TypeError: Field ``foobar`` of type ``Date`` must provide ``IFromUnicode``. However, the ``FieldDataConverter`` is registered for ``IField``, since many fields (like ``Decimal``) for which we want to create custom converters provide ``IFromUnicode`` more specifically than their characterizing interface (like ``IDecimal``). The converter can now convert any integer to a the value the test widget deals with, which is an ASCII string: >>> conv.toWidgetValue(34) '34' When the missing value is passed in, an empty string should be returned: >>> conv.toWidgetValue(age.missing_value) '' Of course, values can also be converted from a widget value to field value: >>> conv.toFieldValue('34') 34 An empty string means simply that the value is missing and the missing value of the field is returned: >>> age.missing_value = -1 >>> conv.toFieldValue('') -1 Of course, trying to convert a non-integer string representation fails in a conversion error: >>> conv.toFieldValue('3.4') Traceback (most recent call last): ... InvalidIntLiteral: invalid literal for int(): 3.4 Also, the conversion to the field value also validates the data; in this case negative values are not allowed: >>> conv.toFieldValue('-34') Traceback (most recent call last): ... TooSmall: (-34, 0) That's pretty much the entire API. When dealing with converters within the component architecture, everything is a little bit simpler. So let's register the converter: >>> import zope.component >>> zope.component.provideAdapter(converter.FieldDataConverter) Once we ensure that our widget is a text widget, we can lookup the adapter: >>> import zope.interface >>> from z3c.form import interfaces >>> zope.interface.alsoProvides(text, interfaces.ITextWidget) >>> zope.component.getMultiAdapter((age, text), interfaces.IDataConverter) <FieldDataConverter converts from Int to Widget> For field-widgets there is a helper adapter that makes the lookup even simpler: >>> zope.component.provideAdapter(converter.FieldWidgetDataConverter) After converting our simple widget to a field widget, >>> fieldtext = widget.FieldWidget(age, text) we can now lookup the data converter adapter just by the field widget itself: >>> interfaces.IDataConverter(fieldtext) <FieldDataConverter converts from Int to Widget> Number Data Converters ---------------------- As hinted on above, the package provides a specific data converter for each of the three main numerical types: ``int``, ``float``, ``Decimal``. Specifically, those data converters support full localization of the number formatting. >>> age = zope.schema.Int() >>> intdc = converter.IntegerDataConverter(age, text) >>> intdc <IntegerDataConverter converts from Int to Widget> Since the age is so small, the formatting is trivial: >>> intdc.toWidgetValue(34) '34' But if we increase the number, the grouping seprator will be used: >>> intdc.toWidgetValue(3400) '3,400' An empty string is returned, if the missing value is passed in: >>> intdc.toWidgetValue(None) '' Of course, parsing these outputs again, works as well: >>> intdc.toFieldValue('34') 34 But if we increase the number, the grouping seprator will be used: >>> intdc.toFieldValue('3,400') 3400 Luckily our parser is somewhat forgiving, and even allows for missing group characters: >>> intdc.toFieldValue('3400') 3400 If an empty string is passed in, the missing value of the field is returned: >>> intdc.toFieldValue('') Finally, if the input does not match at all, then a validation error is returned: >>> intdc.toFieldValue('fff') Traceback (most recent call last): ... FormatterValidationError: ('The entered value is not a valid integer literal.', 'fff') The formatter validation error derives from the regular validation error, but allows you to specify the message that is output when asked for the documentation: >>> err = converter.FormatterValidationError('Something went wrong.', None) >>> err.doc() 'Something went wrong.' Let's now look at the float data converter. >>> rating = zope.schema.Float() >>> floatdc = converter.FloatDataConverter(rating, text) >>> floatdc <FloatDataConverter converts from Float to Widget> Again, you can format and parse values: >>> floatdc.toWidgetValue(7.43) '7.43' >>> floatdc.toWidgetValue(10239.43) '10,239.43' >>> floatdc.toFieldValue('7.43') == 7.43 True >>> type(floatdc.toFieldValue('7.43')) <class 'float'> >>> floatdc.toFieldValue('10,239.43') 10239.43 The error message, however, is customized to the floating point: >>> floatdc.toFieldValue('fff') Traceback (most recent call last): ... FormatterValidationError: ('The entered value is not a valid decimal literal.', 'fff') The decimal converter works like the other two before. >>> money = zope.schema.Decimal() >>> decimaldc = converter.DecimalDataConverter(money, text) >>> decimaldc <DecimalDataConverter converts from Decimal to Widget> Formatting and parsing should work just fine: >>> import decimal >>> decimaldc.toWidgetValue(decimal.Decimal('7.43')) '7.43' >>> decimaldc.toWidgetValue(decimal.Decimal('10239.43')) '10,239.43' >>> decimaldc.toFieldValue('7.43') Decimal("7.43") >>> decimaldc.toFieldValue('10,239.43') Decimal("10239.43") Again, the error message, is customized to the floating point: >>> floatdc.toFieldValue('fff') Traceback (most recent call last): ... FormatterValidationError: ('The entered value is not a valid decimal literal.', 'fff') Bool Data Converter --------------------- >>> yesno = zope.schema.Bool() >>> yesnowidget = widget.Widget(TestRequest()) >>> conv = converter.FieldDataConverter(yesno, yesnowidget) >>> conv.toWidgetValue(True) 'True' >>> conv.toWidgetValue(False) 'False' Text Data Converters ---------------------- Users often add empty spaces by mistake, for example when copy-pasting content into the form. >>> name = zope.schema.TextLine() >>> namewidget = widget.Widget(TestRequest()) >>> conv = converter.FieldDataConverter(name, namewidget) >>> conv.toFieldValue('Einstein ') 'Einstein' Date Data Converter ------------------- Since the ``Date`` field does not provide ``IFromUnicode``, we have to provide a custom data converter. This default one is not very sophisticated and is inteded for use with the text widget: >>> date = zope.schema.Date() >>> ddc = converter.DateDataConverter(date, text) >>> ddc <DateDataConverter converts from Date to Widget> Dates are simply converted to ISO format: >>> import datetime >>> bday = datetime.date(1980, 1, 25) >>> ddc.toWidgetValue(bday) '80/01/25' If the date is the missing value, an empty string is returned: >>> ddc.toWidgetValue(None) '' The converter only knows how to convert this particular format back to a datetime value: >>> ddc.toFieldValue('80/01/25') datetime.date(1980, 1, 25) By default the converter converts missing input to missin_input value: >>> ddc.toFieldValue('') is None True If the passed in string cannot be parsed, a formatter validation error is raised: >>> ddc.toFieldValue('8.6.07') Traceback (most recent call last): ... FormatterValidationError: ("The datetime string did not match the pattern 'yy/MM/dd'.", '8.6.07') Time Data Converter ------------------- Since the ``Time`` field does not provide ``IFromUnicode``, we have to provide a custom data converter. This default one is not very sophisticated and is inteded for use with the text widget: >>> time = zope.schema.Time() >>> tdc = converter.TimeDataConverter(time, text) >>> tdc <TimeDataConverter converts from Time to Widget> Dates are simply converted to ISO format: >>> noon = datetime.time(12, 0, 0) >>> tdc.toWidgetValue(noon) '12:00' The converter only knows how to convert this particular format back to a datetime value: >>> tdc.toFieldValue('12:00') datetime.time(12, 0) By default the converter converts missing input to missin_input value: >>> tdc.toFieldValue('') is None True Datetime Data Converter ----------------------- Since the ``Datetime`` field does not provide ``IFromUnicode``, we have to provide a custom data converter. This default one is not very sophisticated and is inteded for use with the text widget: >>> dtField = zope.schema.Datetime() >>> dtdc = converter.DatetimeDataConverter(dtField, text) >>> dtdc <DatetimeDataConverter converts from Datetime to Widget> Dates are simply converted to ISO format: >>> bdayNoon = datetime.datetime(1980, 1, 25, 12, 0, 0) >>> dtdc.toWidgetValue(bdayNoon) '80/01/25 12:00' The converter only knows how to convert this particular format back to a datetime value: >>> dtdc.toFieldValue('80/01/25 12:00') datetime.datetime(1980, 1, 25, 12, 0) By default the converter converts missing input to missin_input value: >>> dtdc.toFieldValue('') is None True Timedelta Data Converter ------------------------ Since the ``Timedelta`` field does not provide ``IFromUnicode``, we have to provide a custom data converter. This default one is not very sophisticated and is inteded for use with the text widget: >>> timedelta = zope.schema.Timedelta() >>> tddc = converter.TimedeltaDataConverter(timedelta, text) >>> tddc <TimedeltaDataConverter converts from Timedelta to Widget> Dates are simply converted to ISO format: >>> allOnes = datetime.timedelta(1, 3600+60+1) >>> tddc.toWidgetValue(allOnes) '1 day, 1:01:01' The converter only knows how to convert this particular format back to a datetime value: >>> fv = tddc.toFieldValue('1 day, 1:01:01') >>> (fv.days, fv.seconds) (1, 3661) If no day is available, the following short form is used: >>> noDay = datetime.timedelta(0, 3600+60+1) >>> tddc.toWidgetValue(noDay) '1:01:01' And now back to the field value: >>> fv = tddc.toFieldValue('1:01:01') >>> (fv.days, fv.seconds) (0, 3661) By default the converter converts missing input to missin_input value: >>> tddc.toFieldValue('') is None True File Upload Data Converter -------------------------- Since the ``Bytes`` field can contain a ``FileUpload`` object, we have to make sure we can convert ``FileUpload`` objects to bytes too. >>> import z3c.form.browser.file >>> fileWidget = z3c.form.browser.file.FileWidget(TestRequest()) >>> bytes = zope.schema.Bytes() >>> fudc = converter.FileUploadDataConverter(bytes, fileWidget) >>> fudc <FileUploadDataConverter converts from Bytes to FileWidget> The file upload widget usually provides a file object. But sometimes is also provides a string: >>> simple = 'foobar' >>> fudc.toFieldValue(simple) b'foobar' The converter can also convert ``FileUpload`` objects. So we need to setup a fields storage stub ... >>> class FieldStorageStub: ... def __init__(self, file): ... self.file = file ... self.headers = {} ... self.filename = 'foo.bar' and a ``FileUpload`` component: >>> from io import BytesIO >>> from zope.publisher.browser import FileUpload >>> myfile = BytesIO(b'File upload contents.') >>> aFieldStorage = FieldStorageStub(myfile) >>> myUpload = FileUpload(aFieldStorage) Let's try to convert the input now: >>> fudc.toFieldValue(myUpload) b'File upload contents.' By default the converter converts missing input to the ``NOT_CHANGED`` value: >>> fudc.toFieldValue('') <NOT_CHANGED> This allows machinery later to ignore the field without sending all the data around. If we get an empty filename in a ``FileUpload`` obejct, we also get the ``missing_value``. But this really means that there was an error somewhere in the upload, since you are normaly not able to upload a file without a filename: >>> class EmptyFilenameFieldStorageStub: ... def __init__(self, file): ... self.file = file ... self.headers = {} ... self.filename = '' >>> myfile = BytesIO(b'') >>> aFieldStorage = EmptyFilenameFieldStorageStub(myfile) >>> myUpload = FileUpload(aFieldStorage) >>> bytes = zope.schema.Bytes() >>> fudc = converter.FileUploadDataConverter(bytes, fileWidget) >>> fudc.toFieldValue(myUpload) is None True There is also a ``ValueError`` if we don't get a seekable file from the ``FieldStorage`` during the upload: >>> myfile = '' >>> aFieldStorage = FieldStorageStub(myfile) >>> myUpload = FileUpload(aFieldStorage) >>> bytes = zope.schema.Bytes() >>> fudc = converter.FileUploadDataConverter(bytes, fileWidget) >>> fudc.toFieldValue(myUpload) is None Traceback (most recent call last): ... ValueError: ('Bytes data are not a file object', ...AttributeError...) When converting to the widget value, not conversion should be done, since bytes are not convertable in that sense. >>> fudc.toWidgetValue(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x04') When the file upload widget is not used and a text-based widget is desired, then the regular field data converter will be chosen. Using a text widget, however, must be setup manually in the form with code like this:: fields['bytesField'].widgetFactory = TextWidget Sequence Data Converter ----------------------- For widgets and fields that work with choices of a sequence, a special data converter is required that works with terms. A prime example is a choice field. Before we can use the converter, we have to register some adapters: >>> from z3c.form import term >>> import zc.sourcefactory.browser.source >>> import zc.sourcefactory.browser.token >>> zope.component.provideAdapter(term.ChoiceTermsVocabulary) >>> zope.component.provideAdapter(term.ChoiceTermsSource) >>> zope.component.provideAdapter(term.ChoiceTerms) >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.source.FactoredTerms) >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.token.fromInteger) The choice fields can be used together with vocabularies and sources. Using vocabulary ~~~~~~~~~~~~~~~~ Let's now create a choice field (using a vocabulary) and a widget: >>> from zope.schema.vocabulary import SimpleVocabulary >>> gender = zope.schema.Choice( ... vocabulary = SimpleVocabulary([ ... SimpleVocabulary.createTerm(0, 'm', 'male'), ... SimpleVocabulary.createTerm(1, 'f', 'female'), ... ]) ) >>> from z3c.form import widget >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = gender We now use the field and widget to instantiate the converter: >>> sdv = converter.SequenceDataConverter(gender, seqWidget) We can now convert a real value to a widget value, which will be the term's token: >>> sdv.toWidgetValue(0) ['m'] The result is always a sequence, since sequence widgets only deal collections of values. Of course, we can convert the widget value back to an internal value: >>> sdv.toFieldValue(['m']) 0 Sometimes a field is not required. In those cases, the internal value is the missing value of the field. The converter interprets that as no value being selected: >>> gender.missing_value = 'missing' >>> sdv.toWidgetValue(gender.missing_value) [] If the internal value is not a valid item in the terms, it is treated as missing: >>> sdv.toWidgetValue(object()) [] If "no value" has been specified in the widget, the missing value of the field is returned: >>> sdv.toFieldValue(['--NOVALUE--']) 'missing' An empty list will also cause the missing value to be returned: >>> sdv.toFieldValue([]) 'missing' Using source ~~~~~~~~~~~~ Let's now create a choice field (using a source) and a widget: >>> from zc.sourcefactory.basic import BasicSourceFactory >>> class GenderSourceFactory(BasicSourceFactory): ... _mapping = {0: 'male', 1: 'female'} ... def getValues(self): ... return self._mapping.keys() ... def getTitle(self, value): ... return self._mapping[value] >>> gender_source = zope.schema.Choice( ... source = GenderSourceFactory()) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = gender_source We now use the field and widget to instantiate the converter: >>> sdv = converter.SequenceDataConverter(gender, seqWidget) We can now convert a real value to a widget value, which will be the term's token: >>> sdv.toWidgetValue(0) ['0'] The result is always a sequence, since sequence widgets only deal collections of values. Of course, we can convert the widget value back to an internal value: >>> sdv.toFieldValue(['0']) 0 Sometimes a field is not required. In those cases, the internalvalue is the missing value of the field. The converter interprets that as no value being selected: >>> gender.missing_value = 'missing' >>> sdv.toWidgetValue(gender.missing_value) [] If "no value" has been specified in the widget, the missing value of the field is returned: >>> sdv.toFieldValue(['--NOVALUE--']) 'missing' An empty list will also cause the missing value to be returned: >>> sdv.toFieldValue([]) 'missing' Collection Sequence Data Converter ---------------------------------- For widgets and fields that work with a sequence of choices, another data converter is required that works with terms. A prime example is a list field. Before we can use the converter, we have to register the terms adapters: >>> from z3c.form import term >>> zope.component.provideAdapter(term.CollectionTerms) >>> zope.component.provideAdapter(term.CollectionTermsVocabulary) >>> zope.component.provideAdapter(term.CollectionTermsSource) Collections can also use either vocabularies or sources. Using vocabulary ~~~~~~~~~~~~~~~~ Let's now create a list field (using the previously defined field using a vocabulary) and a widget: >>> genders = zope.schema.List(value_type=gender) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders We now use the field and widget to instantiate the converter: >>> csdv = converter.CollectionSequenceDataConverter(genders, seqWidget) We can now convert a real value to a widget value, which will be the term's token: >>> csdv.toWidgetValue([0]) ['m'] The result is always a sequence, since sequence widgets only deal collections of values. Of course, we can convert the widget value back to an internal value: >>> csdv.toFieldValue(['m']) [0] Of course, a collection field can also have multiple values: >>> csdv.toWidgetValue([0, 1]) ['m', 'f'] >>> csdv.toFieldValue(['m', 'f']) [0, 1] If any of the values are not a valid choice, they are simply ignored: >>> csdv.toWidgetValue([0, 3]) ['m'] Sometimes a field is not required. In those cases, the internal value is the missing value of the field. The converter interprets that as no values being given: >>> genders.missing_value is None True >>> csdv.toWidgetValue(genders.missing_value) [] For some field, like the ``Set``, the collection type is a tuple. Sigh. In these cases we use the last entry in the tuple as the type to use: >>> genders = zope.schema.Set(value_type=gender) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders >>> csdv = converter.CollectionSequenceDataConverter(genders, seqWidget) >>> csdv.toWidgetValue({0}) ['m'] >>> csdv.toFieldValue(['m']) {0} Getting Terms +++++++++++++ As an optimization of this converter, the converter actually does not look up the terms itself but uses the widget's ``terms`` attribute. If the terms are not yet retrieved, the converter will ask the widget to do so when in need. So let's see how this works when getting the widget value: >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders >>> seqWidget.terms >>> csdv = converter.CollectionSequenceDataConverter(genders, seqWidget) >>> csdv.toWidgetValue([0]) ['m'] >>> seqWidget.terms <z3c.form.term.CollectionTermsVocabulary object ...> The same is true when getting the field value: >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders >>> seqWidget.terms >>> csdv = converter.CollectionSequenceDataConverter(genders, seqWidget) >>> csdv.toFieldValue(['m']) {0} >>> seqWidget.terms <z3c.form.term.CollectionTermsVocabulary object ...> Corner case: Just in case the field has a sequence as ``_type``: >>> class myField(zope.schema.List): ... _type = (list, tuple) >>> genders = myField(value_type=gender) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders We now use the field and widget to instantiate the converter: >>> csdv = converter.CollectionSequenceDataConverter(genders, seqWidget) The converter uses the last type (tuple in this case) to convert: >>> csdv.toFieldValue(['m']) (0,) Using source ~~~~~~~~~~~~ Let's now create a list field (using the previously defined field using a source) and a widget: >>> genders_source = zope.schema.List(value_type=gender_source) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders_source We now use the field and widget to instantiate the converter: >>> csdv = converter.CollectionSequenceDataConverter( ... genders_source, seqWidget) We can now convert a real value to a widget value, which will be the term's token: >>> csdv.toWidgetValue([0]) ['0'] The result is always a sequence, since sequence widgets only deal collections of values. Of course, we can convert the widget value back to an internal value: >>> csdv.toFieldValue(['0']) [0] For some field, like the ``Set``, the collection type is a tuple. Sigh. In these cases we use the last entry in the tuple as the type to use: >>> genders_source = zope.schema.Set(value_type=gender_source) >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders_source >>> csdv = converter.CollectionSequenceDataConverter( ... genders_source, seqWidget) >>> csdv.toWidgetValue({0}) ['0'] >>> csdv.toFieldValue(['0']) {0} Getting Terms +++++++++++++ As an optimization of this converter, the converter actually does not look up the terms itself but uses the widget's ``terms`` attribute. If the terms are not yet retrieved, the converter will ask the widget to do so when in need. So let's see how this works when getting the widget value: >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders_source >>> seqWidget.terms >>> csdv = converter.CollectionSequenceDataConverter( ... genders_source, seqWidget) >>> csdv.toWidgetValue([0]) ['0'] >>> seqWidget.terms <z3c.form.term.CollectionTermsSource object ...> The same is true when getting the field value: >>> seqWidget = widget.SequenceWidget(TestRequest()) >>> seqWidget.field = genders_source >>> seqWidget.terms >>> csdv = converter.CollectionSequenceDataConverter( ... genders_source, seqWidget) >>> csdv.toFieldValue(['0']) {0} >>> seqWidget.terms <z3c.form.term.CollectionTermsSource object ...> Boolean to Single Checkbox Data Converter ----------------------------------------- The conversion from any field to the single checkbox widget value is a special case, because it has to be defined what selecting the value means. In the case of the boolean field, "selected" means ``True`` and if unselected, ``False`` is returned: >>> boolField = zope.schema.Bool() >>> bscbx = converter.BoolSingleCheckboxDataConverter(boolField, seqWidget) >>> bscbx <BoolSingleCheckboxDataConverter converts from Bool to SequenceWidget> Let's now convert boolean field to widget values: >>> bscbx.toWidgetValue(True) ['selected'] >>> bscbx.toWidgetValue(False) [] Converting back is equally simple: >>> bscbx.toFieldValue(['selected']) True >>> bscbx.toFieldValue([]) False Note that this widget has no concept of missing value, since it can only represent two states by desgin. Text Lines Data Converter ------------------------- For sequence widgets and fields that work with a sequence of `TextLine` value fields, a simple data converter is required. Let's create a list of text lines field and a widget: >>> languages = zope.schema.List( ... value_type=zope.schema.TextLine(), ... default=[], ... missing_value=None, ... ) >>> from z3c.form.browser import textlines >>> tlWidget = textlines.TextLinesWidget(TestRequest()) >>> tlWidget.field = languages We now use the field and widget to instantiate the converter: >>> tlc = converter.TextLinesConverter(languages, tlWidget) We can now convert a real value to a widget value: >>> tlc.toWidgetValue(['de', 'fr', 'en']) 'de\nfr\nen' Empty entries are significant: >>> tlc.toWidgetValue(['de', 'fr', 'en', '']) 'de\nfr\nen\n' The result is always a string, since text lines widgets only deal with textarea as input field. Of course, we can convert the widget value back to an internal value: >>> tlc.toFieldValue('de\nfr\nen') ['de', 'fr', 'en'] Each line should be one item: >>> tlc.toFieldValue('this morning\ntomorrow evening\nyesterday') ['this morning', 'tomorrow evening', 'yesterday'] Empty lines are significant: >>> tlc.toFieldValue('de\n\nfr\nen') ['de', '', 'fr', 'en'] Empty lines are also significant at the end: >>> tlc.toFieldValue('de\nfr\nen\n') ['de', 'fr', 'en', ''] An empty string will also cause the missing value to be returned: >>> tlc.toFieldValue('') is None True It also should work for schema fields that define their type as tuple, in former times zope.schema.Int declared its type as (int, long). >>> class MyField(zope.schema.Int): ... _type = (int, float) >>> ids = zope.schema.List( ... value_type=MyField(), ... ) Let's illustrate the problem: >>> MyField._type == (int, float) True The converter will use the first one. >>> tlWidget.field = ids >>> tlc = converter.TextLinesConverter(ids, tlWidget) Of course, it still can convert to the widget value: >>> tlc.toWidgetValue([1,2,3]) '1\n2\n3' And back: >>> tlc.toFieldValue('1\n2\n3') [1, 2, 3] An empty string will also cause the missing value to be returned: >>> tlc.toFieldValue('') is None True Converting Missing value to Widget value returns '': >>> tlc.toWidgetValue(tlc.field.missing_value) '' Just in case the field has sequence as its ``_type``: >>> class myField(zope.schema.List): ... _type = (list, tuple) >>> ids = myField( ... value_type=zope.schema.Int(), ... ) The converter will use the last one, tuple in this case. >>> tlWidget.field = ids >>> tlc = converter.TextLinesConverter(ids, tlWidget) Of course, it still can convert to the widget value: >>> tlc.toWidgetValue([1,2,3]) '1\n2\n3' And back: >>> tlc.toFieldValue('1\n2\n3') (1, 2, 3) What if we have a wrong number: >>> tlc.toFieldValue('1\n2\n3\nfoo') Traceback (most recent call last): ... FormatterValidationError: ("invalid literal for int() with base 10: 'foo'", 'foo') Multi Data Converter -------------------- For multi widgets and fields that work with a sequence of other basic types, a separate data converter is required. Let's create a list of integers field and a widget: >>> numbers = zope.schema.List( ... value_type=zope.schema.Int(), ... default=[], ... missing_value=None, ... ) >>> from z3c.form.browser import multi >>> multiWidget = multi.MultiWidget(TestRequest()) >>> multiWidget.field = numbers Before we can convert, we have to regsiter a widget for the integer field: >>> from z3c.form.browser import text >>> zope.component.provideAdapter( ... text.TextFieldWidget, ... (zope.schema.Int, TestRequest)) We now use the field and widget to instantiate the converter: >>> conv = converter.MultiConverter(numbers, multiWidget) We can now convert a list of integers to the multi-widget internal representation: >>> conv.toWidgetValue([1, 2, 3]) ['1', '2', '3'] If the value is the missing value, an empty list is returned: >>> conv.toWidgetValue(None) [] Now, let's look at the reverse: >>> conv.toFieldValue(['1', '2', '3']) [1, 2, 3] If the list is empty, the missing value is returned: >>> conv.toFieldValue([]) is None True Just in case the field has sequence as its ``_type``: >>> @zope.interface.implementer(zope.schema.interfaces.IList) ... class MySequence(zope.schema._field.AbstractCollection): ... _type = (list, tuple) >>> numbers = MySequence( ... value_type=zope.schema.Int(), ... default=[], ... missing_value=None, ... ) >>> from z3c.form.browser import multi >>> multiWidget = multi.MultiWidget(TestRequest()) >>> multiWidget.field = numbers We now use the field and widget to instantiate the converter: >>> conv = converter.MultiConverter(numbers, multiWidget) We can now convert a list or tuple of integers to the multi-widget internal representation: >>> conv.toWidgetValue([1, 2, 3, 4]) ['1', '2', '3', '4'] >>> conv.toWidgetValue((1, 2, 3, 4)) ['1', '2', '3', '4'] Now, let's look at the reverse. We get a tuple because that's the last type in ``_type``: >>> conv.toFieldValue(['1', '2', '3', '4']) (1, 2, 3, 4) Dict Multi Data Converter ------------------------- For multi widgets and fields that work with a dictionary of other basic types, a separate data converter is required. Let's create a dict of integers field and a widget: >>> numbers = zope.schema.Dict( ... value_type=zope.schema.Int(), ... key_type=zope.schema.Int(), ... default={}, ... missing_value=None, ... ) >>> from z3c.form.browser import multi >>> multiWidget = multi.MultiWidget(TestRequest()) >>> multiWidget.field = numbers Before we can convert, we have to regsiter a widget for the integer field: >>> from z3c.form.browser import text >>> zope.component.provideAdapter( ... text.TextFieldWidget, ... (zope.schema.Int, TestRequest)) We now use the field and widget to instantiate the converter: >>> conv = converter.DictMultiConverter(numbers, multiWidget) We can now convert a dict of integers to the multi-widget internal representation: >>> sorted(conv.toWidgetValue({1:1, 2:4, 3:9})) [('1', '1'), ('2', '4'), ('3', '9')] If the value is the missing value, an empty dict is returned: >>> conv.toWidgetValue(None) [] Now, let's look at the reverse: >>> conv.toFieldValue([('1','1'), ('2','4'), ('3','9')]) {1: 1, 2: 4, 3: 9} If the list is empty, the missing value is returned: >>> conv.toFieldValue([]) is None True
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/converter.rst
converter.rst
__docformat__ = "reStructuredText" import zope.component import zope.interface from z3c.form import interfaces from z3c.form import util @zope.interface.implementer(interfaces.IActionEvent) class ActionEvent: def __init__(self, action): self.action = action def __repr__(self): return '<{} for {!r}>'.format(self.__class__.__name__, self.action) @zope.interface.implementer(interfaces.IActionErrorEvent) class ActionErrorOccurred(ActionEvent): """An event telling the system that an error occurred during action execution.""" def __init__(self, action, error): super().__init__(action) self.error = error class ActionSuccessful(ActionEvent): """An event signalizing that an action has been successfully executed.""" @zope.interface.implementer(interfaces.IAction) class Action: """Action class.""" __name__ = __parent__ = None def __init__(self, request, title, name=None): self.request = request self.title = title if name is None: name = util.createId(title) self.name = name def isExecuted(self): return self.name in self.request def __repr__(self): return f'<{self.__class__.__name__} {self.name!r} {self.title!r}>' @zope.interface.implementer_only(interfaces.IActions) class Actions(util.Manager): """Action manager class.""" __name__ = __parent__ = None def __init__(self, form, request, content): super().__init__() self.form = form self.request = request self.content = content @property def executedActions(self): return [action for action in self.values() if action.isExecuted()] def update(self): """See z3c.form.interfaces.IActions.""" pass def execute(self): """See z3c.form.interfaces.IActions.""" for action in self.executedActions: handler = zope.component.queryMultiAdapter( (self.form, self.request, self.content, action), interface=interfaces.IActionHandler) if handler is not None: try: result = handler() except interfaces.ActionExecutionError as error: zope.event.notify(ActionErrorOccurred(action, error)) else: zope.event.notify(ActionSuccessful(action)) return result def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.__name__) @zope.interface.implementer(interfaces.IActionHandler) class ActionHandlerBase: """Action handler base adapter.""" def __init__(self, form, request, content, action): self.form = form self.request = request self.content = content self.action = action
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/action.py
action.py
======= Buttons ======= Buttons are a method to declare actions for a form. Like fields describe widgets within a form, buttons describe actions. The symmetry goes even further; like fields, buttons are schema fields within schema. When the form is instantiated and updated, the buttons are converted to actions. >>> from z3c.form import button Schema Defined Buttons ---------------------- Let's now create a schema that describes the buttons of a form. Having button schemas allows one to more easily reuse button declarations and to group them logically. ``Button`` objects are just a simple extension to ``Field`` objects, so they behave identical within a schema: >>> import zope.interface >>> class IButtons(zope.interface.Interface): ... apply = button.Button(title='Apply') ... cancel = button.Button(title='Cancel') In reality, only the title and name is relevant. Let's now create a form that provides those buttons. >>> from z3c.form import interfaces >>> @zope.interface.implementer( ... interfaces.IButtonForm, interfaces.IHandlerForm) ... class Form(object): ... buttons = button.Buttons(IButtons) ... prefix = 'form' ... ... @button.handler(IButtons['apply']) ... def apply(self, action): ... print('successfully applied') ... ... @button.handler(IButtons['cancel']) ... def cancel(self, action): ... self.request.response.redirect('index.html') Let's now create an action manager for the button manager in the form. To do that we first need a request and a form instance: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> form = Form() We also have to register a button action factory for the buttons: >>> zope.component.provideAdapter( ... button.ButtonAction, provides=interfaces.IButtonAction) Action managers are instantiated using the form, request, and context/content. A special button-action-manager implementation is available in the ``button`` package: >>> actions = button.ButtonActions(form, request, None) >>> actions.update() Once the action manager is updated, the buttons should be available as actions: >>> list(actions.keys()) ['apply', 'cancel'] >>> actions['apply'] <ButtonAction 'form.buttons.apply' 'Apply'> It is possible to customize how a button is transformed into an action by registering an adapter for the request and the button that provides ``IButtonAction``. >>> import zope.component >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> class CustomButtonAction(button.ButtonAction): ... """Custom Button Action Class.""" >>> zope.component.provideAdapter( ... CustomButtonAction, provides=interfaces.IButtonAction) Now if we rerun update we will get this other ButtonAction implementation. Note, there are two strategies what now could happen. We can remove the existing action and get the new adapter based action or we can reuse the existing action. Since the ButtonActions class offers an API for remove existing actions, we reuse the existing action because it very uncommon to replace existing action during an for update call with an adapter. If someone really will add an action adapter during process time via directly provided interface, he is also responsible for remove existing actions. As you can see we still will get the old button action if we only call update: >>> actions.update() >>> list(actions.keys()) ['apply', 'cancel'] >>> actions['apply'] <ButtonAction 'form.buttons.apply' 'Apply'> This means we have to remove the previous action before we call update: >>> del actions['apply'] >>> actions.update() Make sure we do not append a button twice to the key and value lists by calling update twice: >>> list(actions.keys()) ['apply', 'cancel'] >>> actions['apply'] <CustomButtonAction 'form.buttons.apply' 'Apply'> Alternatively, customize an individual button by setting its actionFactory attribute. >>> def customButtonActionFactory(request, field): ... print("This button factory creates a button only once.") ... button = CustomButtonAction(request, field) ... button.css = "happy" ... return button >>> form.buttons['apply'].actionFactory = customButtonActionFactory Again, remove the old button action befor we call update: >>> del actions['apply'] >>> actions.update() This button factory creates a button only once. >>> actions.update() >>> actions['apply'].css 'happy' Since we only create a button once from an adapter or a factory, we can change the button attributes without to lose changes: >>> actions['apply'].css = 'very happy' >>> actions['apply'].css 'very happy' >>> actions.update() >>> actions['apply'].css 'very happy' But let's not digress too much and get rid of this customization >>> form.buttons['apply'].actionFactory = None >>> actions.update() Button actions are locations: >>> apply = actions['apply'] >>> apply.__name__ 'apply' >>> apply.__parent__ <ButtonActions None> A button action is also a submit widget. The attributes translate as follows: >>> interfaces.ISubmitWidget.providedBy(apply) True >>> apply.value == apply.title True >>> apply.id == apply.name.replace('.', '-') True Next we want to display our button actions. To be able to do this, we have to register a template for the submit widget: >>> from z3c.form import testing, widget >>> templatePath = testing.getPath('submit_input.pt') >>> factory = widget.WidgetTemplateFactory(templatePath, 'text/html') >>> from zope.pagetemplate.interfaces import IPageTemplate >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, TestRequest, None, None, ... interfaces.ISubmitWidget), ... IPageTemplate, name='input') A widget template has many discriminators: context, request, view, field, and widget. We can now render each action: >>> print(actions['apply'].render()) <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> So displaying is nice, but how do button handlers get executed? The action manager provides attributes and method to check whether actions were executed. Initially there are no executed actions: >>> list(actions.executedActions) [] So in this case executing the actions does not do anything: >>> actions.execute() But if the request contains the information that the button was pressed, the execution works: >>> request = TestRequest(form={'form.buttons.apply': 'Apply'}) >>> actions = button.ButtonActions(form, request, None) >>> actions.update() >>> actions.execute() Aehm, something should have happened. But in order for the system to look at the handlers declared in the form, a special action handler has to be registered with the system: >>> zope.component.provideAdapter(button.ButtonActionHandler) And voila, the execution works: >>> actions.execute() successfully applied Finally, if there is no handler for a button, then the button click is silently ignored: >>> form.handlers = button.Handlers() >>> actions.execute() While this might seem awkward at first, this is an intended feature. Sometimes there are several sub-forms that listen to a particular button and one form or another might simply not care about the button at all and not provide a handler. In-Form Button Declarations --------------------------- Some readers might find it cumbersome to declare a full schema just to create some buttons. A faster method is to write simple arguments to the button manager: >>> @zope.interface.implementer( ... interfaces.IButtonForm, interfaces.IHandlerForm) ... class Form(object): ... buttons = button.Buttons( ... button.Button('apply', title='Apply')) ... prefix = 'form.' ... ... @button.handler(buttons['apply']) ... def apply(self, action): ... print('successfully applied') The first argument of the ``Button`` class constructor is the name of the button. Optionally, this can also be one of the following keyword arguments: >>> button.Button(name='apply').__name__ 'apply' >>> button.Button(__name__='apply').__name__ 'apply' If no name is specified, the button will not have a name immediately, ... >>> button.Button(title='Apply').__name__ '' because if the button is created within an interface, the name is assigned later: >>> class IActions(zope.interface.Interface): ... apply = button.Button(title='Apply') >>> IActions['apply'].__name__ 'apply' However, once the button is added to a button manager, a name will be assigned: >>> btns = button.Buttons(button.Button(title='Apply')) >>> btns['apply'].__name__ 'apply' >>> btns = button.Buttons(button.Button(title='Apply and more')) >>> btns['4170706c7920616e64206d6f7265'].__name__ '4170706c7920616e64206d6f7265' This declaration behaves identical to the one before: >>> form = Form() >>> request = TestRequest() >>> actions = button.ButtonActions(form, request, None) >>> actions.update() >>> actions.execute() When sending in the right information, the actions are executed: >>> request = TestRequest(form={'form.buttons.apply': 'Apply'}) >>> actions = button.ButtonActions(form, request, None) >>> actions.update() >>> actions.execute() successfully applied An even simpler method -- resembling closest the API provided by formlib -- is to create the button and handler at the same time: >>> @zope.interface.implementer( ... interfaces.IButtonForm, interfaces.IHandlerForm) ... class Form(object): ... prefix = 'form.' ... ... @button.buttonAndHandler('Apply') ... def apply(self, action): ... print('successfully applied') In this case the ``buttonAndHandler`` decorator creates a button and a handler for it. By default the name is computed from the title of the button, which is required. All (keyword) arguments are forwarded to the button constructor. Let's now render the form: >>> request = TestRequest(form={'form.buttons.apply': 'Apply'}) >>> actions = button.ButtonActions(form, request, None) >>> actions.update() >>> actions.execute() successfully applied If the title is a more complex string, then the name of the button becomes a hex-encoded string: >>> class Form(object): ... ... @button.buttonAndHandler('Apply and Next') ... def apply(self, action): ... print('successfully applied') >>> list(Form.buttons.keys()) ['4170706c7920616e64204e657874'] Of course, you can use the ``__name__`` argument to specify a name yourself. The decorator, however, also allows the keyword ``name``: >>> class Form(object): ... ... @button.buttonAndHandler('Apply and Next', name='applyNext') ... def apply(self, action): ... print('successfully applied') >>> list(Form.buttons.keys()) ['applyNext'] This helper function also supports a keyword argument ``provides``, which allows the developer to specify a sequence of interfaces that the generated button should directly provide. Those provided interfaces can be used for a multitude of things, including handler discrimination and UI layout: >>> class IMyButton(zope.interface.Interface): ... pass >>> class Form(object): ... ... @button.buttonAndHandler('Apply', provides=(IMyButton,)) ... def apply(self, action): ... print('successfully applied') >>> IMyButton.providedBy(Form.buttons['apply']) True Button Conditions ----------------- Sometimes it is desirable to only show a button when a certain condition is fulfilled. The ``Button`` field supports conditions via a simple argument. The ``condition`` argument must be a callable taking the form as argument and returning a truth-value. If the condition is not fulfilled, the button will not be converted to an action: >>> class Form(object): ... prefix = 'form' ... showApply = True ... ... @button.buttonAndHandler( ... 'Apply', condition=lambda form: form.showApply) ... def apply(self, action): ... print('successfully applied') In this case a form variable specifies the availability. Initially the button is available as action: >>> myform = Form() >>> actions = button.ButtonActions(myform, TestRequest(), None) >>> actions.update() >>> list(actions.keys()) ['apply'] If we set the show-apply attribute to false, the action will not be available. >>> myform.showApply = False >>> actions.update() >>> list(actions.keys()) [] >>> list(actions.values()) [] This feature is very helpful in multi-forms and wizards. Customizing the Title --------------------- As for widgets, it is often desirable to change attributes of the button actions without altering any original code. Again we will be using attribute value adapters to complete the task. Originally, our title is as follows: >>> myform = Form() >>> actions = button.ButtonActions(myform, TestRequest(), None) >>> actions.update() >>> actions['apply'].title 'Apply' Let's now create a custom label for the action: >>> ApplyLabel = button.StaticButtonActionAttribute( ... 'Apply now', button=myform.buttons['apply']) >>> zope.component.provideAdapter(ApplyLabel, name='title') Once the button action manager is updated, the new title is chosen: >>> actions.update() >>> actions['apply'].title 'Apply now' The Button Manager ------------------ The button manager contains several additional API methods that make the management of buttons easy. First, you are able to add button managers: >>> bm1 = button.Buttons(IButtons) >>> bm2 = button.Buttons(button.Button('help', title='Help')) >>> bm1 + bm2 Buttons([...]) >>> list(bm1 + bm2) ['apply', 'cancel', 'help'] The result of the addition is another button manager. Also note that the order of the buttons is preserved throughout the addition. Adding anything else is not well-defined: >>> bm1 + 1 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'Buttons' and 'int' Second, you can select the buttons in a particular order: >>> bm = bm1 + bm2 >>> list(bm) ['apply', 'cancel', 'help'] >>> list(bm.select('help', 'apply', 'cancel')) ['help', 'apply', 'cancel'] The ``select()`` method can also be used to eliminate another button: >>> list(bm.select('help', 'apply')) ['help', 'apply'] Of course, in the example above we eliminated one and reorganized the buttons. Third, you can omit one or more buttons: >>> list(bm.omit('cancel')) ['apply', 'help'] Finally, while the constructor is very flexible, you cannot just pass in anything: >>> button.Buttons(1, 2) Traceback (most recent call last): ... TypeError: ('Unrecognized argument type', 1) When creating a new form derived from another, you often want to keep existing buttons and add new ones. In order not to change the super-form class, you need to copy the button manager: >>> list(bm.keys()) ['apply', 'cancel', 'help'] >>> list(bm.copy().keys()) ['apply', 'cancel', 'help'] The Handlers Object ------------------- All handlers of a form are collected in the ``handlers`` attribute, which is a ``Handlers`` instance: >>> isinstance(form.handlers, button.Handlers) True >>> form.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>]> Internally the object uses an adapter registry to manage the handlers for buttons. If a handler is registered for a button, it simply behaves as an instance-adapter. The object itself is pretty simple. You can get a handler as follows: >>> apply = form.buttons['apply'] >>> form.handlers.getHandler(apply) <Handler for <Button 'apply' 'Apply'>> But you can also register handlers for groups of buttons, either by interface or class: >>> class SpecialButton(button.Button): ... pass >>> def handleSpecialButton(form, action): ... return 'Special button action' >>> form.handlers.addHandler( ... SpecialButton, button.Handler(SpecialButton, handleSpecialButton)) >>> form.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>, <Handler for <class 'SpecialButton'>>]> Now all special buttons should use that handler: >>> button1 = SpecialButton(name='button1', title='Button 1') >>> button2 = SpecialButton(name='button2', title='Button 2') >>> form.handlers.getHandler(button1)(form, None) 'Special button action' >>> form.handlers.getHandler(button2)(form, None) 'Special button action' However, registering a more specific handler for button 1 will override the general handler: >>> def handleButton1(form, action): ... return 'Button 1 action' >>> form.handlers.addHandler( ... button1, button.Handler(button1, handleButton1)) >>> form.handlers.getHandler(button1)(form, None) 'Button 1 action' >>> form.handlers.getHandler(button2)(form, None) 'Special button action' You can also add handlers objects: >>> handlers2 = button.Handlers() >>> button3 = SpecialButton(name='button3', title='Button 3') >>> handlers2.addHandler( ... button3, button.Handler(button3, None)) >>> form.handlers + handlers2 <Handlers [<Handler for <Button 'apply' 'Apply'>>, <Handler for <class 'SpecialButton'>>, <Handler for <SpecialButton 'button1' 'Button 1'>>, <Handler for <SpecialButton 'button3' 'Button 3'>>]> However, adding other components is not supported: >>> form.handlers + 1 Traceback (most recent call last): ... NotImplementedError The handlers also provide a method to copy the handlers to a new instance: >>> copy = form.handlers.copy() >>> isinstance(copy, button.Handlers) True >>> copy is form.handlers False This is commonly needed when one wants to extend the handlers of a super-form. Image Buttons ------------- A special type of button is the image button. Instead of creating a "submit"- or "button"-type input, an "image" button is created. An image button is a simple extension of a button, requiring an `image` argument to the constructor: >>> imgSubmit = button.ImageButton( ... name='submit', ... title='Submit', ... image='submit.png') >>> imgSubmit <ImageButton 'submit' 'submit.png'> Some browsers do not submit the value of the input, but only the coordinates of the image where the mouse click occurred. Thus we also need a special button action: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> imgSubmitAction = button.ImageButtonAction(request, imgSubmit) >>> imgSubmitAction <ImageButtonAction 'submit' 'Submit'> Initially, we did not click on the image: >>> imgSubmitAction.isExecuted() False Now the button is clicked: >>> request = TestRequest(form={'submit.x': '3', 'submit.y': '4'}) >>> imgSubmitAction = button.ImageButtonAction(request, imgSubmit) >>> imgSubmitAction.isExecuted() True The "image" type of the "input"-element also requires there to be a `src` attribute, which is the URL to the image to be used. The attribute is also supported by the Python API. However, in order for the attribute to work, the image must be available as a resource, so let's do that now: # Traversing setup >>> from zope.traversing import testing >>> testing.setUp() # Resource namespace >>> import zope.component >>> from zope.traversing.interfaces import ITraversable >>> from zope.traversing.namespace import resource >>> zope.component.provideAdapter( ... resource, (None,), ITraversable, name="resource") >>> zope.component.provideAdapter( ... resource, (None, None), ITraversable, name="resource") # New absolute URL adapter for resources, if available >>> from zope.browserresource.resource import AbsoluteURL >>> zope.component.provideAdapter(AbsoluteURL) # Register the "submit.png" resource >>> from zope.browserresource.resource import Resource >>> testing.browserResource('submit.png', Resource) Now the attribute can be called: >>> imgSubmitAction.src 'http://127.0.0.1/@@/submit.png'
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/button.rst
button.rst
============== Field Managers ============== One of the features in ``zope.formlib`` that works really well is the syntax used to define the contents of the form. The formlib uses form fields, to describe how the form should be put together. Since we liked this way of working, this package offers this feature as well in a very similar way. A field manager organizes all fields to be displayed within a form. Each field is associated with additional meta-data. The simplest way to create a field manager is to specify the schema from which to extract all fields. Thus, the first step is to create a schema: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... id = zope.schema.Int( ... title='Id', ... readonly=True) ... ... name = zope.schema.TextLine( ... title='Name') ... ... country = zope.schema.Choice( ... title='Country', ... values=('Germany', 'Switzerland', 'USA'), ... required=False) We can now create the field manager: >>> from z3c.form import field >>> manager = field.Fields(IPerson) Like all managers in this package, it provides the enumerable mapping API: >>> manager['id'] <Field 'id'> >>> manager['unknown'] Traceback (most recent call last): ... KeyError: 'unknown' >>> manager.get('id') <Field 'id'> >>> manager.get('unknown', 'default') 'default' >>> 'id' in manager True >>> 'unknown' in manager False >>> list(manager.keys()) ['id', 'name', 'country'] >>> [key for key in manager] ['id', 'name', 'country'] >>> list(manager.values()) [<Field 'id'>, <Field 'name'>, <Field 'country'>] >>> list(manager.items()) [('id', <Field 'id'>), ('name', <Field 'name'>), ('country', <Field 'country'>)] >>> len(manager) 3 You can also select the fields that you would like to have: >>> manager = manager.select('name', 'country') >>> list(manager.keys()) ['name', 'country'] Changing the order is simply a matter of changing the selection order: >>> manager = manager.select('country', 'name') >>> list(manager.keys()) ['country', 'name'] Selecting a field becomes a little bit more tricky when field names overlap. For example, let's say that a person can be adapted to a pet: >>> class IPet(zope.interface.Interface): ... id = zope.schema.TextLine( ... title='Id') ... ... name = zope.schema.TextLine( ... title='Name') The pet field(s) can only be added to the fields manager with a prefix: >>> manager += field.Fields(IPet, prefix='pet') >>> list(manager.keys()) ['country', 'name', 'pet.id', 'pet.name'] When selecting fields, this prefix has to be used: >>> manager = manager.select('name', 'pet.name') >>> list(manager.keys()) ['name', 'pet.name'] However, sometimes it is tedious to specify the prefix together with the field; for example here: >>> manager = field.Fields(IPerson).select('name') >>> manager += field.Fields(IPet, prefix='pet').select('pet.name', 'pet.id') >>> list(manager.keys()) ['name', 'pet.name', 'pet.id'] It is easier to specify the prefix as an afterthought: >>> manager = field.Fields(IPerson).select('name') >>> manager += field.Fields(IPet, prefix='pet').select( ... 'name', 'id', prefix='pet') >>> list(manager.keys()) ['name', 'pet.name', 'pet.id'] Alternatively, you can specify the interface: >>> manager = field.Fields(IPerson).select('name') >>> manager += field.Fields(IPet, prefix='pet').select( ... 'name', 'id', interface=IPet) >>> list(manager.keys()) ['name', 'pet.name', 'pet.id'] Sometimes it is easier to simply omit a set of fields instead of selecting all the ones you want: >>> manager = field.Fields(IPerson) >>> manager = manager.omit('id') >>> list(manager.keys()) ['name', 'country'] Again, you can solve name conflicts using the full prefixed name, ... >>> manager = field.Fields(IPerson).omit('country') >>> manager += field.Fields(IPet, prefix='pet') >>> list(manager.omit('pet.id').keys()) ['id', 'name', 'pet.name'] using the prefix keyword argument, ... >>> manager = field.Fields(IPerson).omit('country') >>> manager += field.Fields(IPet, prefix='pet') >>> list(manager.omit('id', prefix='pet').keys()) ['id', 'name', 'pet.name'] or, using the interface: >>> manager = field.Fields(IPerson).omit('country') >>> manager += field.Fields(IPet, prefix='pet') >>> list(manager.omit('id', interface=IPet).keys()) ['id', 'name', 'pet.name'] You can also add two field managers together: >>> manager = field.Fields(IPerson).select('name', 'country') >>> manager2 = field.Fields(IPerson).select('id') >>> list((manager + manager2).keys()) ['name', 'country', 'id'] Adding anything else to a field manager is not well defined: >>> manager + 1 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'Fields' and 'int' You also cannot make any additions that would cause a name conflict: >>> manager + manager Traceback (most recent call last): ... ValueError: ('Duplicate name', 'name') When creating a new form derived from another, you often want to keep existing fields and add new ones. In order to not change the super-form class, you need to copy the field manager: >>> list(manager.keys()) ['name', 'country'] >>> list(manager.copy().keys()) ['name', 'country'] More on the Constructor ----------------------- The constructor does not only accept schemas to be passed in; one can also just pass in schema fields: >>> list(field.Fields(IPerson['name']).keys()) ['name'] However, the schema field has to have a name: >>> email = zope.schema.TextLine(title='E-Mail') >>> field.Fields(email) Traceback (most recent call last): ... ValueError: Field has no name Adding a name helps: >>> email.__name__ = 'email' >>> list(field.Fields(email).keys()) ['email'] Or, you can just pass in other field managers, which is the feature that the add mechanism uses: >>> list(field.Fields(manager).keys()) ['name', 'country'] Last, but not least, the constructor also accepts form fields, which are used by ``select()`` and ``omit()``: >>> list(field.Fields(manager['name'], manager2['id']).keys()) ['name', 'id'] If the constructor does not recognize any of the types above, it raises a ``TypeError`` exception: >>> field.Fields(object()) Traceback (most recent call last): ... TypeError: ('Unrecognized argument type', <object object at ...>) Additionally, you can specify several keyword arguments in the field manager constructor that are used to set up the fields: * ``omitReadOnly`` When set to ``True`` all read-only fields are omitted. >>> list(field.Fields(IPerson, omitReadOnly=True).keys()) ['name', 'country'] * ``keepReadOnly`` Sometimes you want to keep a particular read-only field around, even though in general you want to omit them. In this case you can specify the fields to keep: >>> list(field.Fields( ... IPerson, omitReadOnly=True, keepReadOnly=('id',)).keys()) ['id', 'name', 'country'] * ``prefix`` Sets the prefix of the fields. This argument is passed on to each field. >>> manager = field.Fields(IPerson, prefix='myform.') >>> manager['myform.name'] <Field 'myform.name'> * ``interface`` Usually the interface is inferred from the field itself. The interface is used to determine whether an adapter must be looked up for a given context. But sometimes fields are generated in isolation to an interface or the interface of the field is not the one you want. In this case you can specify the interface: >>> class IMyPerson(IPerson): ... pass >>> manager = field.Fields(email, interface=IMyPerson) >>> manager['email'].interface <InterfaceClass builtins.IMyPerson> * ``mode`` The mode in which the widget will be rendered. By default there are two available, "input" and "display". When mode is not specified, "input" is chosen. >>> from z3c.form import interfaces >>> manager = field.Fields(IPerson, mode=interfaces.DISPLAY_MODE) >>> manager['country'].mode 'display' * ``ignoreContext`` While the ``ignoreContext`` flag is usually set on the form, it is sometimes desirable to set the flag for a particular field. >>> manager = field.Fields(IPerson) >>> manager['country'].ignoreContext >>> manager = field.Fields(IPerson, ignoreContext=True) >>> manager['country'].ignoreContext True >>> manager = field.Fields(IPerson, ignoreContext=False) >>> manager['country'].ignoreContext False * ``showDefault`` The ``showDefault`` can be set on fields. >>> manager = field.Fields(IPerson) >>> manager['country'].showDefault >>> manager = field.Fields(IPerson, showDefault=True) >>> manager['country'].showDefault True >>> manager = field.Fields(IPerson, showDefault=False) >>> manager['country'].showDefault False Fields Widget Manager --------------------- When a form (or any other widget-using view) is updated, one of the tasks is to create the widgets. Traditionally, generating the widgets involved looking at the form fields (or similar) of a form and generating the widgets using the information of those specifications. This solution is good for the common (about 85%) use cases, since it makes writing new forms very simple and allows a lot of control at a class-definition level. It has, however, its limitations. It does not, for example, allow for customization without rewriting a form. This can range from omitting fields on a particular form to generically adding a new widget to the form, such as an "object name" button on add forms. This package solves this issue by providing a widget manager, which is responsible providing the widgets for a particular view. The default widget manager for forms is able to look at a form's field definitions and create widgets for them. Thus, let's create a schema first: >>> import zope.interface >>> import zope.schema >>> class LastNameTooShort(zope.schema.interfaces.ValidationError): ... """The last name is too short.""" >>> def lastNameConstraint(value): ... if value and value == value.lower(): ... raise zope.interface.Invalid(u"Name must have at least one capital letter") ... return True >>> class IPerson(zope.interface.Interface): ... id = zope.schema.TextLine( ... title='ID', ... description=u"The person's ID.", ... readonly=True, ... required=True) ... ... lastName = zope.schema.TextLine( ... title='Last Name', ... description=u"The person's last name.", ... default='', ... required=True, ... constraint=lastNameConstraint) ... ... firstName = zope.schema.TextLine( ... title='First Name', ... description=u"The person's first name.", ... default='-- unknown --', ... required=False) ... ... @zope.interface.invariant ... def twiceAsLong(person): ... # note: we're protecting here values against being None ... # just in case ignoreRequiredOnExtract lets that through ... if len(person.lastName or '') >= 2 * len(person.firstName or ''): ... raise LastNameTooShort() Next we need a form that specifies the fields to be added: >>> from z3c.form import field >>> class PersonForm(object): ... prefix = 'form.' ... fields = field.Fields(IPerson) >>> personForm = PersonForm() For more details on how to define fields within a form, see :doc:`form`. We can now create the fields widget manager. Its discriminators are the form for which the widgets are created, the request, and the context that is being manipulated. In the simplest case the context is ``None`` and ignored, as it is true for an add form. >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> context = object() >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True Widget Mapping ~~~~~~~~~~~~~~ The main responsibility of the manager is to provide the ``IEnumerableMapping`` interface and an ``update()`` method. Initially the mapping, going from widget id to widget value, is empty: >>> from zope.interface.common.mapping import IEnumerableMapping >>> IEnumerableMapping.providedBy(manager) True >>> list(manager.keys()) [] Only by "updating" the manager, will the widgets become available; before we can use the update method, however, we have to register the ``IFieldWidget`` adapter for the ``ITextLine`` field: >>> from z3c.form import interfaces, widget >>> @zope.component.adapter(zope.schema.TextLine, TestRequest) ... @zope.interface.implementer(interfaces.IFieldWidget) ... def TextFieldWidget(field, request): ... return widget.FieldWidget(field, widget.Widget(request)) >>> zope.component.provideAdapter(TextFieldWidget) >>> from z3c.form import converter >>> zope.component.provideAdapter(converter.FieldDataConverter) >>> zope.component.provideAdapter(converter.FieldWidgetDataConverter) >>> manager.update() Other than usual mappings in Python, the widget manager's widgets are always in a particular order: >>> list(manager.keys()) ['id', 'lastName', 'firstName'] As you can see, if we call update twice, we still get the same amount and order of keys: >>> manager.update() >>> list(manager.keys()) ['id', 'lastName', 'firstName'] Let's make sure that all enumerable mapping functions work correctly: >>> manager['lastName'] <Widget 'form.widgets.lastName'> >>> manager['unknown'] Traceback (most recent call last): ... KeyError: 'unknown' >>> manager.get('lastName') <Widget 'form.widgets.lastName'> >>> manager.get('unknown', 'default') 'default' >>> 'lastName' in manager True >>> 'unknown' in manager False >>> [key for key in manager] ['id', 'lastName', 'firstName'] >>> list(manager.values()) [<Widget 'form.widgets.id'>, <Widget 'form.widgets.lastName'>, <Widget 'form.widgets.firstName'>] >>> list(manager.items()) [('id', <Widget 'form.widgets.id'>), ('lastName', <Widget 'form.widgets.lastName'>), ('firstName', <Widget 'form.widgets.firstName'>)] >>> len(manager) 3 It is also possible to delete widgets from the manager: >>> del manager['firstName'] >>> len(manager) 2 >>> list(manager.values()) [<Widget 'form.widgets.id'>, <Widget 'form.widgets.lastName'>] >>> list(manager.keys()) ['id', 'lastName'] >>> list(manager.items()) [('id', <Widget 'form.widgets.id'>), ('lastName', <Widget 'form.widgets.lastName'>)] Note that deleting a non-existent widget causes a ``KeyError`` to be raised: >>> del manager['firstName'] Traceback (most recent call last): ... KeyError: 'firstName' Also, the field widget manager, like any selection manager, can be cloned: >>> clone = manager.copy() >>> clone is not manager True >>> clone.form == manager.form True >>> clone.request == manager.request True >>> clone.content == manager.content True >>> list(clone.items()) == list(manager.items()) True Properties of widgets within a manager ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When a widget is added to the widget manager, it is located: >>> lname = manager['lastName'] >>> lname.__name__ 'lastName' >>> lname.__parent__ FieldWidgets([...]) All widgets created by this widget manager are context aware: >>> interfaces.IContextAware.providedBy(lname) True >>> lname.context is context True Determination of the widget mode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, all widgets will also assume the mode of the manager: >>> manager['lastName'].mode 'input' >>> manager.mode = interfaces.DISPLAY_MODE >>> manager.update() >>> manager['lastName'].mode 'display' The exception is when some fields specifically desire a different mode. In the first case, all "readonly" fields will be shown in display mode: >>> manager.mode = interfaces.INPUT_MODE >>> manager.update() >>> manager['id'].mode 'display' An exception is made when the flag, "ignoreReadonly" is set: >>> manager.ignoreReadonly = True >>> manager.update() >>> manager['id'].mode 'input' In the second case, the last name will inherit the mode from the widget manager, while the first name will want to use a display widget: >>> personForm.fields = field.Fields(IPerson).select('lastName') >>> personForm.fields += field.Fields( ... IPerson, mode=interfaces.DISPLAY_MODE).select('firstName') >>> manager.mode = interfaces.INPUT_MODE >>> manager.update() >>> manager['lastName'].mode 'input' >>> manager['firstName'].mode 'display' In a third case, the widget will be shown in display mode, if the attribute of the context is not writable. Clearly this can never occur in add forms, since there the context is ignored, but is an important use case in edit forms. Thus, we need an implementation of the ``IPerson`` interface including some security declarations: >>> from zope.security import checker >>> @zope.interface.implementer(IPerson) ... class Person(object): ... ... def __init__(self, firstName, lastName): ... self.id = firstName[0].lower() + lastName.lower() ... self.firstName = firstName ... self.lastName = lastName >>> PersonChecker = checker.Checker( ... get_permissions = {'id': checker.CheckerPublic, ... 'firstName': checker.CheckerPublic, ... 'lastName': checker.CheckerPublic}, ... set_permissions = {'firstName': 'test.Edit', ... 'lastName': checker.CheckerPublic} ... ) >>> srichter = checker.ProxyFactory( ... Person('Stephan', 'Richter'), PersonChecker) In this case the last name is always editable, but for the first name the user will need the edit ("test.Edit") permission. We also need to register the data manager and setup a new security policy: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.AttributeField) >>> from zope.security import management >>> from z3c.form import testing >>> management.endInteraction() >>> newPolicy = testing.SimpleSecurityPolicy() >>> oldpolicy = management.setSecurityPolicy(newPolicy) >>> management.newInteraction() Now we can create the widget manager: >>> personForm = PersonForm() >>> request = TestRequest() >>> manager = field.FieldWidgets(personForm, request, srichter) After updating the widget manager, the fields are available as widgets, the first name being in display and the last name is input mode: >>> manager.update() >>> manager['id'].mode 'display' >>> manager['firstName'].mode 'display' >>> manager['lastName'].mode 'input' However, explicitly overriding the mode in the field declaration overrides this selection for you: >>> personForm.fields['firstName'].mode = interfaces.INPUT_MODE >>> manager.update() >>> manager['id'].mode 'display' >>> manager['firstName'].mode 'input' >>> manager['lastName'].mode 'input' ``showDefault`` --------------- ``showDefault`` by default is ``True``: >>> manager['firstName'].showDefault True ``showDefault`` gets set on the widget based on the field's setting. >>> personForm.fields['firstName'].showDefault = False >>> manager.update() >>> manager['firstName'].showDefault False >>> personForm.fields['firstName'].showDefault = True >>> manager.update() >>> manager['firstName'].showDefault True Required fields --------------- There is a flag for required fields. This flag get set if at least one field is required. This let us render a required info legend in forms if required fields get used. >>> manager.hasRequiredFields True Data extraction and validation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Besides managing widgets, the widget manager also controls the process of extracting and validating extracted data. Let's start with the validation first, which only validates the data as a whole, assuming each individual value being already validated. Before we can use the method, we have to register a "manager validator": >>> from z3c.form import validator >>> zope.component.provideAdapter(validator.InvariantsValidator) >>> personForm.fields = field.Fields(IPerson) >>> manager.update() >>> manager.validate( ... {'firstName': 'Stephan', 'lastName': 'Richter'}) () The result of this method is a tuple of errors that occurred during the validation. An empty tuple means the validation succeeded. Let's now make the validation fail: >>> errors = manager.validate( ... {'firstName': 'Stephan', 'lastName': 'Richter-Richter'}) >>> [error.doc() for error in errors] ['The last name is too short.'] A special case occurs when the schema fields are not associated with an interface: >>> name = zope.schema.TextLine(__name__='name') >>> class PersonNameForm(object): ... prefix = 'form.' ... fields = field.Fields(name) >>> personNameForm = PersonNameForm() >>> manager = field.FieldWidgets(personNameForm, request, context) In this case, the widget manager's ``validate()`` method should simply ignore the field and not try to look up any invariants: >>> manager.validate({'name': 'Stephan'}) () Let's now have a look at the widget manager's ``extract()``, which returns a data dictionary and the collection of errors. Before we can validate, we have to register a validator for the widget: >>> zope.component.provideAdapter(validator.SimpleFieldValidator) When all goes well, the data dictionary is complete and the error collection empty: >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.update() >>> data, errors = manager.extract() >>> data['firstName'] 'Stephan' >>> data['lastName'] 'Richter' >>> errors () Since all errors are immediately converted to error view snippets, we have to provide the adapter from a validation error to an error view snippet first: >>> from z3c.form import error >>> zope.component.provideAdapter(error.ErrorViewSnippet) >>> zope.component.provideAdapter(error.InvalidErrorViewSnippet) Let's now cause a widget-level error by not submitting the required last name: >>> request = TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', 'form.widgets.id': 'srichter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.update() >>> manager.extract() ({'firstName': 'Stephan'}, (<ErrorViewSnippet for RequiredMissing>,)) We can also turn off ``required`` checking for data extraction: >>> request = TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', 'form.widgets.id': 'srichter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.ignoreRequiredOnExtract = True >>> manager.update() Here we get the required field as ``None`` and no errors: >>> pprint(manager.extract()) ({'firstName': 'Stephan', 'lastName': None}, ()) >>> manager.ignoreRequiredOnExtract = False Or, we could violate a constraint. This constraint raises Invalid, which is a convenient way to raise errors where we mainly care about providing a custom error message. >>> request = TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'richter', ... 'form.widgets.id': 'srichter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.update() >>> extracted = manager.extract() >>> extracted ({'firstName': 'Stephan'}, (<InvalidErrorViewSnippet for Invalid>,)) >>> extracted[1][0].createMessage() 'Name must have at least one capital letter' Finally, let's ensure that invariant failures are also caught: >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter-Richter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.update() >>> data, errors = manager.extract() >>> errors[0].error.doc() 'The last name is too short.' Note that the errors coming from invariants are all error view snippets as well, just as it is the case for field-specific validation errors. And that's really all there is! By default, the ``extract()`` method not only returns the errors that it catches, but also sets them on individual widgets and on the manager: >>> manager.errors (<ErrorViewSnippet for LastNameTooShort>,) This behavior can be turned off. To demonstrate, let's make a new request that causes a widget-level error: >>> request = TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', 'form.widgets.id': 'srichter'}) >>> manager = field.FieldWidgets(personForm, request, context) >>> manager.ignoreContext = True >>> manager.update() We have to set the setErrors property to False before calling extract, we still get the same result from the method call, ... >>> manager.setErrors = False >>> manager.extract() ({'firstName': 'Stephan'}, (<ErrorViewSnippet for RequiredMissing>,)) but there are no side effects on the manager and the widgets: >>> manager.errors () >>> manager['lastName'].error is None True Customization of Ignoring the Context ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that you can also manually control ignoring the context per field. >>> class CustomPersonForm(object): ... prefix = 'form.' ... fields = field.Fields(IPerson).select('id') ... fields += field.Fields(IPerson, ignoreContext=True).select( ... 'firstName', 'lastName') >>> customPersonForm = CustomPersonForm() Let's now create a manager and update it: >>> customManager = field.FieldWidgets(customPersonForm, request, context) >>> customManager.update() >>> customManager['id'].ignoreContext False >>> customManager['firstName'].ignoreContext True >>> customManager['lastName'].ignoreContext True Fields -- Custom Widget Factories --------------------------------- It is possible to declare custom widgets for fields within the field's declaration. Let's have a look at the default form first. Initially, the standard registered widgets are used: >>> manager = field.FieldWidgets(personForm, request, srichter) >>> manager.update() >>> manager['firstName'] <Widget 'form.widgets.firstName'> Now we would like to have our own custom input widget: >>> class CustomInputWidget(widget.Widget): ... pass >>> def CustomInputWidgetFactory(field, request): ... return widget.FieldWidget(field, CustomInputWidget(request)) It can be simply assigned as follows: >>> personForm.fields['firstName'].widgetFactory = CustomInputWidgetFactory >>> personForm.fields['lastName'].widgetFactory = CustomInputWidgetFactory Now this widget should be used instead of the registered default one: >>> manager = field.FieldWidgets(personForm, request, srichter) >>> manager.update() >>> manager['firstName'] <CustomInputWidget 'form.widgets.firstName'> In the background the widget factory assignment really just registered the default factory in the ``WidgetFactories`` object, which manages the custom widgets for all modes. Now all modes show this input widget: >>> manager = field.FieldWidgets(personForm, request, srichter) >>> manager.mode = interfaces.DISPLAY_MODE >>> manager.update() >>> manager['firstName'] <CustomInputWidget 'form.widgets.firstName'> However, we can also register a specific widget for the display mode: >>> class CustomDisplayWidget(widget.Widget): ... pass >>> def CustomDisplayWidgetFactory(field, request): ... return widget.FieldWidget(field, CustomDisplayWidget(request)) >>> personForm.fields['firstName']\ ... .widgetFactory[interfaces.DISPLAY_MODE] = CustomDisplayWidgetFactory >>> personForm.fields['lastName']\ ... .widgetFactory[interfaces.DISPLAY_MODE] = CustomDisplayWidgetFactory Now the display mode should produce the custom display widget, ... >>> manager = field.FieldWidgets(personForm, request, srichter) >>> manager.mode = interfaces.DISPLAY_MODE >>> manager.update() >>> manager['firstName'] <CustomDisplayWidget 'form.widgets.firstName'> >>> manager['lastName'] <CustomDisplayWidget 'form.widgets.lastName'> ... while the input mode still shows the default custom input widget on the ``lastName`` field but not on the ``firstName`` field since we don't have the ``test.Edit`` permission: >>> manager = field.FieldWidgets(personForm, request, srichter) >>> manager.mode = interfaces.INPUT_MODE >>> manager.update() >>> manager['firstName'] <CustomDisplayWidget 'form.widgets.firstName'> >>> manager['lastName'] <CustomInputWidget 'form.widgets.lastName'> The widgets factories component, >>> factories = personForm.fields['firstName'].widgetFactory >>> factories {'display': <function CustomDisplayWidgetFactory at ...>} is pretty much a standard dictionary that also manages a default value: >>> factories.default <function CustomInputWidgetFactory at ...> When getting a value for a key, if the key is not found, the default is returned: >>> sorted(factories.keys()) ['display'] >>> factories[interfaces.DISPLAY_MODE] <function CustomDisplayWidgetFactory at ...> >>> factories[interfaces.INPUT_MODE] <function CustomInputWidgetFactory at ...> >>> factories.get(interfaces.DISPLAY_MODE) <function CustomDisplayWidgetFactory at ...> >>> factories.get(interfaces.INPUT_MODE) <function CustomInputWidgetFactory at ...> If no default is specified, >>> factories.default = None then the dictionary behaves as usual: >>> factories[interfaces.DISPLAY_MODE] <function CustomDisplayWidgetFactory at ...> >>> factories[interfaces.INPUT_MODE] Traceback (most recent call last): ... KeyError: 'input' >>> factories.get(interfaces.DISPLAY_MODE) <function CustomDisplayWidgetFactory at ...> >>> factories.get(interfaces.INPUT_MODE)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/field.rst
field.rst
===================== Hint (title) Adapters ===================== A widget can provide a hint. Hints are not a standard concept, the implementations can be very different in each project. Hints are most of the time implemented with JavaScript since the default ``input title`` hint in browsers are almost unusable. Our hint support is limited and only offers some helpers. Which means we will offer an adapter that shows the schema field description as the title. Since this is very specific we only provide a ``FieldDescriptionAsHint`` adapter which you can configure as a named IValue adapter. >>> import zope.interface >>> import zope.component >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import hint We also need to setup the form defaults: >>> from z3c.form import testing >>> testing.setupFormDefaults() Let's create a couple of simple widgets and forms first: >>> class IContent(zope.interface.Interface): ... ... textLine = zope.schema.TextLine( ... title=u'Title', ... description=u'A TextLine description') ... ... anotherLine = zope.schema.TextLine( ... title=u'Other') >>> @zope.interface.implementer(IContent) ... class Content(object): ... textLine = None ... otherLine = None ... >>> content = Content() >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> class HintForm(form.Form): ... fields = field.Fields(IContent) >>> hintForm = HintForm(content, request) As you can see, there is no title value set for our widgets: >>> hintForm.update() >>> print(hintForm.widgets['textLine'].render()) <input id="form-widgets-textLine" name="form.widgets.textLine" class="text-widget required textline-field" value="" type="text" /> >>> print(hintForm.widgets['anotherLine'].render()) <input id="form-widgets-anotherLine" name="form.widgets.anotherLine" class="text-widget required textline-field" value="" type="text" /> Let's configure our IValue ``hint`` adapter: >>> from z3c.form.hint import FieldDescriptionAsHint >>> zope.component.provideAdapter(FieldDescriptionAsHint, name='title') If we update our form, we can see that the title is used based on the schema field description: >>> hintForm.update() >>> print(hintForm.widgets['textLine'].render()) <input id="form-widgets-textLine" name="form.widgets.textLine" class="text-widget required textline-field" title="A TextLine description" value="" type="text" /> If the field has no description as it is with the second one, no "title" will be set for the widget: >>> print(hintForm.widgets['anotherLine'].render()) <input id="form-widgets-anotherLine" name="form.widgets.anotherLine" class="text-widget required textline-field" value="" type="text" /> Check all fields ---------------- Just to make sure that all the widgets are handled correctly, we will go through all of them. This sample can be useful if you need to implement a JavaScript based hint concept: >>> import datetime >>> import decimal >>> from zope.schema import vocabulary Let's setup a simple vocabulary: >>> vocab = vocabulary.SimpleVocabulary([ ... vocabulary.SimpleVocabulary.createTerm(1, '1', u'One'), ... vocabulary.SimpleVocabulary.createTerm(2, '2', u'Two'), ... vocabulary.SimpleVocabulary.createTerm(3, '3', u'Three'), ... vocabulary.SimpleVocabulary.createTerm(4, '4', u'Four'), ... vocabulary.SimpleVocabulary.createTerm(5, '5', u'Five') ... ]) >>> class IAllInOne(zope.interface.Interface): ... ... asciiField = zope.schema.ASCII( ... title=u'ASCII', ... description=u'This is an ASCII field.', ... default='This is\n ASCII.') ... ... asciiLineField = zope.schema.ASCIILine( ... title=u'ASCII Line', ... description=u'This is an ASCII-Line field.', ... default='An ASCII line.') ... ... boolField = zope.schema.Bool( ... title=u'Boolean', ... description=u'This is a Bool field.', ... required=True, ... default=True) ... ... checkboxBoolField = zope.schema.Bool( ... title=u'Boolean (Checkbox)', ... description=u'This is a Bool field displayed suing a checkbox.', ... required=True, ... default=True) ... ... bytesLineField = zope.schema.BytesLine( ... title=u'Bytes Line', ... description=u'This is a bytes line field.', ... default=b'A Bytes line.') ... ... choiceField = zope.schema.Choice( ... title=u'Choice', ... description=u'This is a choice field.', ... default=3, ... vocabulary=vocab) ... ... optionalChoiceField = zope.schema.Choice( ... title=u'Choice (Not Required)', ... description=u'This is a non-required choice field.', ... vocabulary=vocab, ... required=False) ... ... promptChoiceField = zope.schema.Choice( ... title=u'Choice (Explicit Prompt)', ... description=u'This is a choice field with an explicit prompt.', ... vocabulary=vocab, ... required=False) ... ... dateField = zope.schema.Date( ... title=u'Date', ... description=u'This is a Date field.', ... default=datetime.date(2007, 4, 1)) ... ... datetimeField = zope.schema.Datetime( ... title=u'Date/Time', ... description=u'This is a Datetime field.', ... default=datetime.datetime(2007, 4, 1, 12)) ... ... decimalField = zope.schema.Decimal( ... title=u'Decimal', ... description=u'This is a Decimal field.', ... default=decimal.Decimal('12.87')) ... ... dottedNameField = zope.schema.DottedName( ... title=u'Dotted Name', ... description=u'This is a DottedName field.', ... default='z3c.form') ... ... floatField = zope.schema.Float( ... title=u'Float', ... description=u'This is a Float field.', ... default=12.8) ... ... frozenSetField = zope.schema.FrozenSet( ... title=u'Frozen Set', ... description=u'This is a FrozenSet field.', ... value_type=choiceField, ... default=frozenset([1, 3]) ) ... ... idField = zope.schema.Id( ... title=u'Id', ... description=u'This is a Id field.', ... default='z3c.form') ... ... intField = zope.schema.Int( ... title=u'Integer', ... description=u'This is a Int field.', ... default=12345) ... ... listField = zope.schema.List( ... title=u'List', ... description=u'This is a List field.', ... value_type=choiceField, ... default=[1, 3]) ... ... passwordField = zope.schema.Password( ... title=u'Password', ... description=u'This is a Password field.', ... default=u'mypwd', ... required=False) ... ... setField = zope.schema.Set( ... title=u'Set', ... description=u'This is a Set field.', ... value_type=choiceField, ... default=set([1, 3]) ) ... ... sourceTextField = zope.schema.SourceText( ... title=u'Source Text', ... description=u'This is a SourceText field.', ... default=u'<source />') ... ... textField = zope.schema.Text( ... title=u'Text', ... description=u'This is a Text field.', ... default=u'Some\n Text.') ... ... textLineField = zope.schema.TextLine( ... title=u'Text Line', ... description=u'This is a TextLine field.', ... default=u'Some Text line.') ... ... timeField = zope.schema.Time( ... title=u'Time', ... description=u'This is a Time field.', ... default=datetime.time(12, 0)) ... ... timedeltaField = zope.schema.Timedelta( ... title=u'Time Delta', ... description=u'This is a Timedelta field.', ... default=datetime.timedelta(days=3)) ... ... tupleField = zope.schema.Tuple( ... title=u'Tuple', ... description=u'This is a Tuple field.', ... value_type=choiceField, ... default=(1, 3)) ... ... uriField = zope.schema.URI( ... title=u'URI', ... description=u'This is a URI field.', ... default='http://zope.org') ... ... hiddenField = zope.schema.TextLine( ... title=u'Hidden Text Line', ... description=u'This is a hidden TextLine field.', ... default=u'Some Hidden Text.') >>> @zope.interface.implementer(IAllInOne) ... class AllInOne(object): ... asciiField = None ... asciiLineField = None ... boolField = None ... checkboxBoolField = None ... choiceField = None ... optionalChoiceField = None ... promptChoiceField = None ... dateField = None ... decimalField = None ... dottedNameField = None ... floatField = None ... frozenSetField = None ... idField = None ... intField = None ... listField = None ... passwordField = None ... setField = None ... sourceTextField = None ... textField = None ... textLineField = None ... timeField = None ... timedeltaField = None ... tupleField = None ... uriField = None ... hiddenField = None >>> allInOne = AllInOne() >>> class AllInOneForm(form.Form): ... fields = field.Fields(IAllInOne) Now test the hints in our widgets: >>> allInOneForm = AllInOneForm(allInOne, request) >>> allInOneForm.update() >>> print(allInOneForm.widgets['asciiField'].render()) <textarea id="form-widgets-asciiField" name="form.widgets.asciiField" class="textarea-widget required ascii-field" title="This is an ASCII field.">This is ASCII.</textarea> >>> print(allInOneForm.widgets['asciiLineField'].render()) <input id="form-widgets-asciiLineField" name="form.widgets.asciiLineField" class="text-widget required asciiline-field" title="This is an ASCII-Line field." value="An ASCII line." type="text" /> >>> print(allInOneForm.widgets['boolField'].render()) <span class="option"> <label for="form-widgets-boolField-0"> <input id="form-widgets-boolField-0" name="form.widgets.boolField" class="radio-widget required bool-field" title="This is a Bool field." value="true" checked="checked" type="radio" /> <span class="label">yes</span> </label> </span> <span class="option"> <label for="form-widgets-boolField-1"> <input id="form-widgets-boolField-1" name="form.widgets.boolField" class="radio-widget required bool-field" title="This is a Bool field." value="false" type="radio" /> <span class="label">no</span> </label> </span> <input name="form.widgets.boolField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['checkboxBoolField'].render()) <span class="option"> <label for="form-widgets-checkboxBoolField-0"> <input id="form-widgets-checkboxBoolField-0" name="form.widgets.checkboxBoolField" class="radio-widget required bool-field" title="This is a Bool field displayed suing a checkbox." value="true" checked="checked" type="radio" /> <span class="label">yes</span> </label> </span> <span class="option"> <label for="form-widgets-checkboxBoolField-1"> <input id="form-widgets-checkboxBoolField-1" name="form.widgets.checkboxBoolField" class="radio-widget required bool-field" title="This is a Bool field displayed suing a checkbox." value="false" type="radio" /> <span class="label">no</span> </label> </span> <input name="form.widgets.checkboxBoolField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['bytesLineField'].render()) <input id="form-widgets-bytesLineField" name="form.widgets.bytesLineField" class="text-widget required bytesline-field" title="This is a bytes line field." value="A Bytes line." type="text" /> >>> print(allInOneForm.widgets['choiceField'].render()) <select id="form-widgets-choiceField" name="form.widgets.choiceField:list" class="select-widget required choice-field" size="1" title="This is a choice field."> <option id="form-widgets-choiceField-0" value="1">One</option> <option id="form-widgets-choiceField-1" value="2">Two</option> <option id="form-widgets-choiceField-2" value="3" selected="selected">Three</option> <option id="form-widgets-choiceField-3" value="4">Four</option> <option id="form-widgets-choiceField-4" value="5">Five</option> </select> <input name="form.widgets.choiceField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['optionalChoiceField'].render()) <select id="form-widgets-optionalChoiceField" name="form.widgets.optionalChoiceField:list" class="select-widget choice-field" size="1" title="This is a non-required choice field."> <option id="form-widgets-optionalChoiceField-novalue" value="--NOVALUE--" selected="selected">No value</option> <option id="form-widgets-optionalChoiceField-0" value="1">One</option> <option id="form-widgets-optionalChoiceField-1" value="2">Two</option> <option id="form-widgets-optionalChoiceField-2" value="3">Three</option> <option id="form-widgets-optionalChoiceField-3" value="4">Four</option> <option id="form-widgets-optionalChoiceField-4" value="5">Five</option> </select> <input name="form.widgets.optionalChoiceField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['promptChoiceField'].render()) <select id="form-widgets-promptChoiceField" name="form.widgets.promptChoiceField:list" class="select-widget choice-field" size="1" title="This is a choice field with an explicit prompt."> <option id="form-widgets-promptChoiceField-novalue" value="--NOVALUE--" selected="selected">No value</option> <option id="form-widgets-promptChoiceField-0" value="1">One</option> <option id="form-widgets-promptChoiceField-1" value="2">Two</option> <option id="form-widgets-promptChoiceField-2" value="3">Three</option> <option id="form-widgets-promptChoiceField-3" value="4">Four</option> <option id="form-widgets-promptChoiceField-4" value="5">Five</option> </select> <input name="form.widgets.promptChoiceField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['dateField'].render()) <input id="form-widgets-dateField" name="form.widgets.dateField" class="text-widget required date-field" title="This is a Date field." value="07/04/01" type="text" /> >>> print(allInOneForm.widgets['datetimeField'].render()) <input id="form-widgets-datetimeField" name="form.widgets.datetimeField" class="text-widget required datetime-field" title="This is a Datetime field." value="07/04/01 12:00" type="text" /> >>> print(allInOneForm.widgets['decimalField'].render()) <input id="form-widgets-decimalField" name="form.widgets.decimalField" class="text-widget required decimal-field" title="This is a Decimal field." value="12.87" type="text" /> >>> print(allInOneForm.widgets['dottedNameField'].render()) <input id="form-widgets-dottedNameField" name="form.widgets.dottedNameField" class="text-widget required dottedname-field" title="This is a DottedName field." value="z3c.form" type="text" /> >>> print(allInOneForm.widgets['floatField'].render()) <input id="form-widgets-floatField" name="form.widgets.floatField" class="text-widget required float-field" title="This is a Float field." value="12.8" type="text" /> >>> print(allInOneForm.widgets['frozenSetField'].render()) <select id="form-widgets-frozenSetField" name="form.widgets.frozenSetField:list" class="select-widget required frozenset-field" multiple="multiple" size="5" title="This is a FrozenSet field."> <option id="form-widgets-frozenSetField-0" value="1" selected="selected">One</option> <option id="form-widgets-frozenSetField-1" value="2">Two</option> <option id="form-widgets-frozenSetField-2" value="3" selected="selected">Three</option> <option id="form-widgets-frozenSetField-3" value="4">Four</option> <option id="form-widgets-frozenSetField-4" value="5">Five</option> </select> <input name="form.widgets.frozenSetField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['idField'].render()) <input id="form-widgets-idField" name="form.widgets.idField" class="text-widget required id-field" title="This is a Id field." value="z3c.form" type="text" /> >>> print(allInOneForm.widgets['intField'].render()) <input id="form-widgets-intField" name="form.widgets.intField" class="text-widget required int-field" title="This is a Int field." value="12,345" type="text" /> >>> print(allInOneForm.widgets['listField'].render()) <span class="option"> <label for="form-widgets-listField-0"> <input id="form-widgets-listField-0" name="form.widgets.listField" class="radio-widget required list-field" title="This is a List field." value="1" checked="checked" type="radio" /> <span class="label">One</span> </label> </span> <span class="option"> <label for="form-widgets-listField-1"> <input id="form-widgets-listField-1" name="form.widgets.listField" class="radio-widget required list-field" title="This is a List field." value="2" type="radio" /> <span class="label">Two</span> </label> </span> <span class="option"> <label for="form-widgets-listField-2"> <input id="form-widgets-listField-2" name="form.widgets.listField" class="radio-widget required list-field" title="This is a List field." value="3" checked="checked" type="radio" /> <span class="label">Three</span> </label> </span> <span class="option"> <label for="form-widgets-listField-3"> <input id="form-widgets-listField-3" name="form.widgets.listField" class="radio-widget required list-field" title="This is a List field." value="4" type="radio" /> <span class="label">Four</span> </label> </span> <span class="option"> <label for="form-widgets-listField-4"> <input id="form-widgets-listField-4" name="form.widgets.listField" class="radio-widget required list-field" title="This is a List field." value="5" type="radio" /> <span class="label">Five</span> </label> </span> <input name="form.widgets.listField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['passwordField'].render()) <input id="form-widgets-passwordField" name="form.widgets.passwordField" class="text-widget password-field" title="This is a Password field." value="mypwd" type="text" /> >>> print(allInOneForm.widgets['setField'].render()) <select id="form-widgets-setField" name="form.widgets.setField:list" class="select-widget required set-field" multiple="multiple" size="5" title="This is a Set field."> <option id="form-widgets-setField-0" value="1" selected="selected">One</option> <option id="form-widgets-setField-1" value="2">Two</option> <option id="form-widgets-setField-2" value="3" selected="selected">Three</option> <option id="form-widgets-setField-3" value="4">Four</option> <option id="form-widgets-setField-4" value="5">Five</option> </select> <input name="form.widgets.setField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['sourceTextField'].render()) <textarea id="form-widgets-sourceTextField" name="form.widgets.sourceTextField" class="textarea-widget required sourcetext-field" title="This is a SourceText field.">&lt;source /&gt;</textarea> >>> print(allInOneForm.widgets['textField'].render()) <textarea id="form-widgets-textField" name="form.widgets.textField" class="textarea-widget required text-field" title="This is a Text field.">Some Text.</textarea> >>> print(allInOneForm.widgets['textLineField'].render()) <input id="form-widgets-textLineField" name="form.widgets.textLineField" class="text-widget required textline-field" title="This is a TextLine field." value="Some Text line." type="text" /> >>> print(allInOneForm.widgets['timeField'].render()) <input id="form-widgets-timeField" name="form.widgets.timeField" class="text-widget required time-field" title="This is a Time field." value="12:00" type="text" /> >>> print(allInOneForm.widgets['timedeltaField'].render()) <input id="form-widgets-timedeltaField" name="form.widgets.timedeltaField" class="text-widget required timedelta-field" title="This is a Timedelta field." value="3 days, 0:00:00" type="text" /> >>> print(allInOneForm.widgets['tupleField'].render()) <span class="option"> <label for="form-widgets-tupleField-0"> <input id="form-widgets-tupleField-0" name="form.widgets.tupleField" class="radio-widget required tuple-field" title="This is a Tuple field." value="1" checked="checked" type="radio" /> <span class="label">One</span> </label> </span> <span class="option"> <label for="form-widgets-tupleField-1"> <input id="form-widgets-tupleField-1" name="form.widgets.tupleField" class="radio-widget required tuple-field" title="This is a Tuple field." value="2" type="radio" /> <span class="label">Two</span> </label> </span> <span class="option"> <label for="form-widgets-tupleField-2"> <input id="form-widgets-tupleField-2" name="form.widgets.tupleField" class="radio-widget required tuple-field" title="This is a Tuple field." value="3" checked="checked" type="radio" /> <span class="label">Three</span> </label> </span> <span class="option"> <label for="form-widgets-tupleField-3"> <input id="form-widgets-tupleField-3" name="form.widgets.tupleField" class="radio-widget required tuple-field" title="This is a Tuple field." value="4" type="radio" /> <span class="label">Four</span> </label> </span> <span class="option"> <label for="form-widgets-tupleField-4"> <input id="form-widgets-tupleField-4" name="form.widgets.tupleField" class="radio-widget required tuple-field" title="This is a Tuple field." value="5" type="radio" /> <span class="label">Five</span> </label> </span> <input name="form.widgets.tupleField-empty-marker" type="hidden" value="1" /> >>> print(allInOneForm.widgets['uriField'].render()) <input id="form-widgets-uriField" name="form.widgets.uriField" class="text-widget required uri-field" title="This is a URI field." value="http://zope.org" type="text" /> >>> print(allInOneForm.widgets['hiddenField'].render()) <input id="form-widgets-hiddenField" name="form.widgets.hiddenField" class="text-widget required textline-field" title="This is a hidden TextLine field." value="Some Hidden Text." type="text" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/hint.rst
hint.rst
=============== Action Managers =============== Action managers are components that manage all actions that can be taken within a view, usually a form. They are also responsible for executing actions when asked to do so. Creating an action manager -------------------------- An action manager is a form-related adapter that has the following discriminator: form, request, and content. While there is a base implementation for an action manager, the ``action`` module does not provide a full implementation. So we first have to build a simple implementation based on the ``Actions`` manager base class which allows us to add actions. Note that the following implementation is for demonstration purposes. If you want to see a real action manager implementation, then have a look at ``ButtonActions``. Let's now implement our simple action manager: >>> from z3c.form import action >>> class SimpleActions(action.Actions): ... """Simple sample.""" ... ... def append(self, name, action): ... """See z3c.form.interfaces.IActions.""" ... self[name] = action Before we can initialise the action manager, we have to create instances for our three discriminators, just enough to get it working: >>> import zope.interface >>> from z3c.form import interfaces >>> @zope.interface.implementer(interfaces.IForm) ... class Form(object): ... pass >>> form = Form() >>> @zope.interface.implementer(zope.interface.Interface) ... class Content(object): ... pass >>> content = Content() >>> from z3c.form.testing import TestRequest >>> request = TestRequest() We are now ready to create the action manager, which is a simple triple-adapter: >>> manager = SimpleActions(form, request, content) >>> manager <SimpleActions None> As we can see in the manager representation above, the name of the manager is ``None``, since we have not specified one: >>> manager.__name__ = 'example' >>> manager <SimpleActions 'example'> Managing and Accessing Actions ------------------------------ Initially there are no actions in the manager: >>> list(manager.keys()) [] Our simple implementation of has an additional ``append()`` method, which we will use to add actions: >>> apply = action.Action(request, 'Apply') >>> manager.append(apply.name, apply) The action is added immediately: >>> list(manager.keys()) ['apply'] However, you should not rely on it being added, and always update the manager once all actions were defined: >>> manager.update() Note: If the title of the action is a more complex unicode string and no name is specified for the action, then a hexadecimal name is created from the title: >>> action.Action(request, 'Apply Now!').name '4170706c79204e6f7721' Since the action manager is an enumerable mapping, ... >>> from zope.interface.common.mapping import IEnumerableMapping >>> IEnumerableMapping.providedBy(manager) True there are several API methods available: >>> manager['apply'] <Action 'apply' 'Apply'> >>> manager['foo'] Traceback (most recent call last): ... KeyError: 'foo' >>> manager.get('apply') <Action 'apply' 'Apply'> >>> manager.get('foo', 'default') 'default' >>> 'apply' in manager True >>> 'foo' in manager False >>> list(manager.values()) [<Action 'apply' 'Apply'>] >>> list(manager.items()) [('apply', <Action 'apply' 'Apply'>)] >>> len(manager) 1 Executing actions ----------------- When an action is executed, an execution adapter is looked up. If there is no adapter, nothing happens. So let's create a request that submits the apply button: >>> request = TestRequest(form={'apply': 'Apply'}) >>> manager = SimpleActions(form, request, content) We also want to have two buttons in this case, so that we can ensure that only one is executed: >>> apply = action.Action(request, 'Apply') >>> manager.append(apply.name, apply) >>> cancel = action.Action(request, 'Cancel') >>> manager.append(cancel.name, cancel) >>> manager.update() Now that the manager is updated, we can ask it for the "executed" actions: >>> manager.executedActions [<Action 'apply' 'Apply'>] Executing the actions does nothing, because there are no handlers yet: >>> manager.execute() Let's now register an action handler that listens to the "Apply" action. An action handler has four discriminators: form, request, content, and action. All those objects are available to the handler under those names. When using the base action handler from the ``action`` module, ``__call__()`` is the only method that needs to be implemented: >>> from z3c.form import util >>> class SimpleActionHandler(action.ActionHandlerBase): ... zope.component.adapts( ... None, TestRequest, None, util.getSpecification(apply)) ... def __call__(self): ... print('successfully applied') >>> zope.component.provideAdapter(SimpleActionHandler) As you can see, we registered the action specifically for the apply action. Now, executing the actions calls this handler: >>> manager.execute() successfully applied Of course it only works for the "Apply" action and not ""Cancel": >>> request = TestRequest(form={'cancel': 'Cancel'}) >>> manager.request = apply.request = cancel.request = request >>> manager.execute() Further, when a handler is successfully executed, an event is sent out, so let's register an event handler: >>> eventlog = [] >>> @zope.component.adapter(interfaces.IActionEvent) ... def handleEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(handleEvent) Let's now execute the "Apply" action again: >>> request = TestRequest(form={'apply': 'Apply'}) >>> manager.request = apply.request = cancel.request = request >>> manager.execute() successfully applied >>> eventlog[-1] <ActionSuccessful for <Action 'apply' 'Apply'>> Action handlers, however, can also raise action errors. These action errors are caught and an event is created notifying the system of the problem. The error is not further propagated. Other errors are not handled by the system to avoid hiding real failures of the code. Let's see how action errors can be used by implementing a handler for the cancel action: >>> class ErrorActionHandler(action.ActionHandlerBase): ... zope.component.adapts( ... None, TestRequest, None, util.getSpecification(cancel)) ... def __call__(self): ... raise interfaces.ActionExecutionError( ... zope.interface.Invalid('Something went wrong')) >>> zope.component.provideAdapter(ErrorActionHandler) As you can see, the action execution error wraps some other execption, in this case a simple invalid error. Executing the "Cancel" action now produces the action error event: >>> request = TestRequest(form={'cancel': 'Cancel'}) >>> manager.request = apply.request = cancel.request = request >>> manager.execute() >>> eventlog[-1] <ActionErrorOccurred for <Action 'cancel' 'Cancel'>> >>> eventlog[-1].error <ActionExecutionError wrapping ...Invalid...>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/action.rst
action.rst
"""Widget Framework Implementation.""" __docformat__ = "reStructuredText" import zope.component import zope.interface import zope.location import zope.schema.interfaces from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.i18n import translate from zope.pagetemplate.interfaces import IPageTemplate from zope.schema.fieldproperty import FieldProperty from z3c.form import interfaces from z3c.form import util from z3c.form import value PLACEHOLDER = object() StaticWidgetAttribute = value.StaticValueCreator( discriminators=('context', 'request', 'view', 'field', 'widget') ) ComputedWidgetAttribute = value.ComputedValueCreator( discriminators=('context', 'request', 'view', 'field', 'widget') ) @zope.interface.implementer(interfaces.IWidget) class Widget(zope.location.Location): """Widget base class.""" # widget specific attributes name = FieldProperty(interfaces.IWidget['name']) label = FieldProperty(interfaces.IWidget['label']) mode = FieldProperty(interfaces.IWidget['mode']) required = FieldProperty(interfaces.IWidget['required']) error = FieldProperty(interfaces.IWidget['error']) value = FieldProperty(interfaces.IWidget['value']) template = None layout = None ignoreRequest = FieldProperty(interfaces.IWidget['ignoreRequest']) ignoreRequiredOnValidation = FieldProperty( interfaces.IWidget['ignoreRequiredOnValidation']) setErrors = FieldProperty(interfaces.IWidget['setErrors']) showDefault = FieldProperty(interfaces.IWidget['showDefault']) # The following attributes are for convenience. They are declared in # extensions to the simple widget. # See ``interfaces.IContextAware`` context = None ignoreContext = False # See ``interfaces.IFormAware`` form = None # See ``interfaces.IFieldWidget`` field = None # Internal attributes _adapterValueAttributes = ('label', 'name', 'required', 'title') def __init__(self, request): self.request = request def update(self): """See z3c.form.interfaces.IWidget.""" # Step 1: Determine the value. value = interfaces.NO_VALUE lookForDefault = False # Step 1.1: If possible, get a value from the request if not self.ignoreRequest: # at this turn we do not need errors to be set on widgets # errors will be set when extract gets called from form.extractData self.setErrors = False widget_value = self.extract() if widget_value is not interfaces.NO_VALUE: # Once we found the value in the request, it takes precendence # over everything and nothing else has to be done. self.value = widget_value value = PLACEHOLDER # Step 1.2: If we have a widget with a field and we have no value yet, # we have some more possible locations to get the value if (interfaces.IFieldWidget.providedBy(self) and value is interfaces.NO_VALUE and value is not PLACEHOLDER): # Step 1.2.1: If the widget knows about its context and the # context is to be used to extract a value, get # it now via a data manager. if (interfaces.IContextAware.providedBy(self) and not self.ignoreContext): value = zope.component.getMultiAdapter( (self.context, self.field), interfaces.IDataManager).query() # Step 1.2.2: If we still do not have a value, we can always use # the default value of the field, if set # NOTE: It should check field.default is not missing_value, but # that requires fixing zope.schema first # We get a clone of the field with the context binded field = self.field.bind(self.context) if value is field.missing_value or value is interfaces.NO_VALUE: default_value = field.default if default_value is not None and self.showDefault: value = field.default lookForDefault = True # Step 1.3: If we still have not found a value, then we try to get it # from an attribute value if ((value is interfaces.NO_VALUE or lookForDefault) and self.showDefault): adapter = zope.component.queryMultiAdapter( (self.context, self.request, self.form, self.field, self), interfaces.IValue, name='default') if adapter: value = adapter.get() # Step 1.4: Convert the value to one that the widget can understand if value not in (interfaces.NO_VALUE, PLACEHOLDER): converter = interfaces.IDataConverter(self) self.value = converter.toWidgetValue(value) # Step 2: Update selected attributes for attrName in self._adapterValueAttributes: # only allow to set values for known attributes if hasattr(self, attrName): value = zope.component.queryMultiAdapter( (self.context, self.request, self.form, self.field, self), interfaces.IValue, name=attrName) if value is not None: setattr(self, attrName, value.get()) def extract(self, default=interfaces.NO_VALUE): """See z3c.form.interfaces.IWidget.""" return self.request.get(self.name, default) def render(self): """Render the plain widget without additional layout""" template = self.template if template is None: template = zope.component.getMultiAdapter( (self.context, self.request, self.form, self.field, self), IPageTemplate, name=self.mode) return template(self) def json_data(self): return { 'mode': self.mode, 'error': self.error.message if self.error else '', 'value': self.value, 'required': self.required, 'name': self.name, 'id': getattr(self, 'id', ''), 'type': 'text', 'label': self.label or '' } def __call__(self): """Get and return layout template which is calling widget/render""" layout = self.layout if layout is None: layout = zope.component.getMultiAdapter( (self.context, self.request, self.form, self.field, self), interfaces.IWidgetLayoutTemplate, name=self.mode) return layout(self) def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.name) @zope.interface.implementer(interfaces.ISequenceWidget) class SequenceWidget(Widget): """Term based sequence widget base. The sequence widget is used for select items from a sequence. Don't get confused, this widget does support to choose one or more values from a sequence. The word sequence is not used for the schema field, it's used for the values where this widget can choose from. This widget base class is used for build single or sequence values based on a sequence which is in most use case a collection. e.g. IList of IChoice for sequence values or IChoice for single values. See also the MultiWidget for build sequence values based on none collection based values. e.g. IList of ITextLine """ value = () terms = None noValueToken = '--NOVALUE--' @property def displayValue(self): value = [] for token in self.value: # Ignore no value entries. They are in the request only. if token == self.noValueToken: continue try: term = self.terms.getTermByToken(token) except LookupError: # silently ignore missing tokens, because INPUT_MODE and # HIDDEN_MODE does that too continue if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term): value.append(translate( term.title, context=self.request, default=term.title)) else: value.append(term.value) return value def updateTerms(self): if self.terms is None: self.terms = zope.component.getMultiAdapter( (self.context, self.request, self.form, self.field, self), interfaces.ITerms) return self.terms def update(self): """See z3c.form.interfaces.IWidget.""" # Create terms first, since we need them for the generic update. self.updateTerms() super().update() def extract(self, default=interfaces.NO_VALUE): """See z3c.form.interfaces.IWidget.""" if (self.name not in self.request and self.name + '-empty-marker' in self.request): return () value = self.request.get(self.name, default) if value != default: if not isinstance(value, (tuple, list)): # this is here to make any single value a tuple value = (value,) if not isinstance(value, tuple): # this is here to make a non-tuple (just a list at this point?) # a tuple. the dance is about making return values uniform value = tuple(value) # do some kind of validation, at least only use existing values for token in value: if token == self.noValueToken: continue try: self.terms.getTermByToken(token) except LookupError: return default return value def json_data(self): data = super().json_data() data['type'] = 'sequence' return data @zope.interface.implementer(interfaces.IMultiWidget) class MultiWidget(Widget): """None Term based sequence widget base. The multi widget is used for ITuple, IList or IDict if no other widget is defined. Some IList, ITuple or IDict are using another specialized widget if they can choose from a collection. e.g. a IList of IChoice. The base class of such widget is the ISequenceWidget. This widget can handle none collection based sequences and offers add or remove values to or from the sequence. Each sequence value get rendered by it's own relevant widget. e.g. IList of ITextLine or ITuple of IInt Each widget get rendered within a sequence value. This means each internal widget will represent one value from the multi widget value. Based on the nature of this (sub) widget setup the internal widget do not have a real context and can't get bound to it. This makes it impossible to use a sequence of collection where the collection needs a context. But that should not be a problem since sequence of collection will use the SequenceWidget as base. """ allowAdding = True allowRemoving = True widgets = None key_widgets = None _value = None _widgets_updated = False _mode = FieldProperty(interfaces.IWidget['mode']) def __init__(self, request): super().__init__(request) self.widgets = [] self.key_widgets = [] self._value = [] @property def is_dict(self): return getattr(self.field, 'key_type', None) is not None @property def counterName(self): return '%s.count' % self.name @property def counterMarker(self): # this get called in render from the template and contains always the # right amount of widgets we use. return '<input type="hidden" name="%s" value="%d" />' % ( self.counterName, len(self.widgets)) @property def mode(self): """This sets the subwidgets modes.""" return self._mode @mode.setter def mode(self, mode): self._mode = mode # ensure that we apply the new mode to the widgets for w in self.widgets: w.mode = mode for w in self.key_widgets: if w is not None: w.mode = mode def getWidget(self, idx, prefix=None, type_field="value_type"): """Setup widget based on index id with or without value.""" valueType = getattr(self.field, type_field) widget = zope.component.getMultiAdapter( (valueType, self.request), interfaces.IFieldWidget) self.setName(widget, idx, prefix) widget.mode = self.mode # set widget.form (objectwidget needs this) if interfaces.IFormAware.providedBy(self): widget.form = self.form zope.interface.alsoProvides( widget, interfaces.IFormAware) widget.update() return widget def setName(self, widget, idx, prefix=None): def names(id): return [str(n) for n in [id] + [prefix, idx] if n is not None] widget.name = '.'.join([str(self.name)] + names(None)) widget.id = '-'.join([str(self.id)] + names(None)) def appendAddingWidget(self): """Simply append a new empty widget with correct (counter) name.""" # since we start with idx 0 (zero) we can use the len as next idx idx = len(self.widgets) widget = self.getWidget(idx) self.widgets.append(widget) if self.is_dict: widget = self.getWidget(idx, "key", "key_type") self.key_widgets.append(widget) else: self.key_widgets.append(None) def removeWidgets(self, names): """ :param names: list of widget.name to remove from the value :return: None """ zipped = list(zip(self.key_widgets, self.widgets)) self.key_widgets = [k for k, v in zipped if v.name not in names] self.widgets = [v for k, v in zipped if v.name not in names] if self.is_dict: self.value = [(k.value, v.value) for k, v in zip(self.key_widgets, self.widgets)] else: self.value = [widget.value for widget in self.widgets] def applyValue(self, widget, value=interfaces.NO_VALUE): """Validate and apply value to given widget. This method gets called on any multi widget value change and is responsible for validating the given value and setup an error message. This is internal apply value and validation process is needed because nothing outside this multi widget does know something about our internal sub widgets. """ if value is not interfaces.NO_VALUE: try: # convert widget value to field value converter = interfaces.IDataConverter(widget) fvalue = converter.toFieldValue(value) # validate field value zope.component.getMultiAdapter( (self.context, self.request, self.form, getattr(widget, 'field', None), widget), interfaces.IValidator).validate(fvalue) # convert field value to widget value widget.value = converter.toWidgetValue(fvalue) except (zope.schema.ValidationError, ValueError) as error: # on exception, setup the widget error message view = zope.component.getMultiAdapter( (error, self.request, widget, widget.field, self.form, self.context), interfaces.IErrorViewSnippet) view.update() widget.error = view # set the wrong value as value widget.value = value def updateWidgets(self): """Setup internal widgets based on the value_type for each value item. """ oldLen = len(self.widgets) # Ensure at least min_length widgets are shown if (zope.schema.interfaces.IMinMaxLen.providedBy(self.field) and self.mode == interfaces.INPUT_MODE and self.allowAdding and oldLen < self.field.min_length): oldLen = self.field.min_length self.widgets = [] self.key_widgets = [] keys = set() idx = 0 if self.value: if self.is_dict: # mainly sorting for testing reasons # and dict's have no order!, but # XXX: this should be done in the converter... here we get # always strings as keys, sorting an str(int/date) is lame # also, newly added item should be the last... try: items = util.sortedNone(self.value) except BaseException: # just in case it's impossible to sort don't fail items = self.value else: items = zip([None] * len(self.value), self.value) for key, v in items: widget = self.getWidget(idx) self.applyValue(widget, v) self.widgets.append(widget) if self.is_dict: # This is needed, since sequence widgets (such as for # choices) return lists of values. hash_key = key if not isinstance(key, list) else tuple(key) widget = self.getWidget(idx, "key", "key_type") self.applyValue(widget, key) if hash_key in keys and widget.error is None: error = zope.interface.Invalid('Duplicate key') view = zope.component.getMultiAdapter( (error, self.request, widget, widget.field, self.form, self.context), interfaces.IErrorViewSnippet) view.update() widget.error = view self.key_widgets.append(widget) keys.add(hash_key) else: # makes the template easier to have this the same length self.key_widgets.append(None) idx += 1 missing = oldLen - len(self.widgets) if missing > 0: # add previous existing new added widgtes for i in range(missing): widget = self.getWidget(idx) self.widgets.append(widget) if self.is_dict: widget = self.getWidget(idx, "key", "key_type") self.key_widgets.append(widget) else: self.key_widgets.append(None) idx += 1 self._widgets_updated = True def updateAllowAddRemove(self): """Update the allowAdding/allowRemoving attributes basing on field constraints and current number of widgets """ if not zope.schema.interfaces.IMinMaxLen.providedBy(self.field): return max_length = self.field.max_length min_length = self.field.min_length num_items = len(self.widgets) self.allowAdding = bool((not max_length) or (num_items < max_length)) self.allowRemoving = bool(num_items and (num_items > min_length)) @property def value(self): """This invokes updateWidgets on any value change. e. g. update/extract. """ return self._value @value.setter def value(self, value): self._value = value # ensure that we apply our new values to the widgets self.updateWidgets() def update(self): """See z3c.form.interfaces.IWidget.""" # Ensure that updateWidgets is called. super().update() if not self._widgets_updated: self.updateWidgets() def extract(self, default=interfaces.NO_VALUE): # This method is responsible to get the widgets value based on the # request and nothing else. # We have to setup the widgets for extract their values, because we # don't know how to do this for every field without the right widgets. # Later we will setup the widgets based on this values. This is needed # because we probably set a new value in the form for our multi widget # which would generate a different set of widgets. if self.request.get(self.counterName) is None: # counter marker not found return interfaces.NO_VALUE counter = int(self.request.get(self.counterName, 0)) # extract value for existing widgets values = [] append = values.append # extract value for existing widgets for idx in range(counter): widget = self.getWidget(idx) if self.is_dict: key_widget = self.getWidget(idx, "key", "key_type") append((key_widget.value, widget.value)) else: append(widget.value) return values def json_data(self): data = super().json_data() data['widgets'] = [widget.json_data() for widget in self.widgets] data['type'] = 'multi' return data def FieldWidget(field, widget): """Set the field for the widget.""" widget.field = field if not interfaces.IFieldWidget.providedBy(widget): zope.interface.alsoProvides(widget, interfaces.IFieldWidget) # Initial values are set. They can be overridden while updating the widget # itself later on. widget.name = field.__name__ widget.id = field.__name__.replace('.', '-') widget.label = field.title widget.required = field.required return widget class WidgetTemplateFactory: """Widget template factory.""" def __init__(self, filename, contentType='text/html', context=None, request=None, view=None, field=None, widget=None): self.template = ViewPageTemplateFile( filename, content_type=contentType) zope.component.adapter( util.getSpecification(context), util.getSpecification(request), util.getSpecification(view), util.getSpecification(field), util.getSpecification(widget))(self) zope.interface.implementer(IPageTemplate)(self) def __call__(self, context, request, view, field, widget): return self.template class WidgetLayoutFactory: """Widget layout template factory.""" def __init__(self, filename, contentType='text/html', context=None, request=None, view=None, field=None, widget=None): self.template = ViewPageTemplateFile( filename, content_type=contentType) zope.component.adapter( util.getSpecification(context), util.getSpecification(request), util.getSpecification(view), util.getSpecification(field), util.getSpecification(widget))(self) zope.interface.implementer(interfaces.IWidgetLayoutTemplate)(self) def __call__(self, context, request, view, field, widget): return self.template @zope.interface.implementer(interfaces.IWidgetEvent) class WidgetEvent: def __init__(self, widget): self.widget = widget def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.widget) @zope.interface.implementer_only(interfaces.IAfterWidgetUpdateEvent) class AfterWidgetUpdateEvent(WidgetEvent): pass
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/widget.py
widget.py
===== Forms ===== The purpose of this package is to make development of forms as simple as possible, while still providing all the hooks to do customization at any level as required by our real-world use cases. Thus, once the system is set up with all its default registrations, it should be trivial to develop a new form. The strategy of this document is to provide the most common, and thus simplest, case first and then demonstrate the available customization options. In order to not overwhelm you with our set of well-chosen defaults, all the default component registrations have been made prior to doing those examples: >>> from z3c.form import testing >>> testing.setupFormDefaults() Note, since version 2.4.2 the IFormLayer doesn't provide IBrowserRequest anymore. This is usefull if you like to use z3c.form components for other requets then the IBrowserRequest. >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> import z3c.form.interfaces >>> z3c.form.interfaces.IFormLayer.isOrExtends(IBrowserRequest) False Before we can start writing forms, we must have the content to work with: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... ... id = zope.schema.TextLine( ... title=u'ID', ... readonly=True, ... required=True) ... ... name = zope.schema.TextLine( ... title=u'Name', ... required=True) ... ... gender = zope.schema.Choice( ... title=u'Gender', ... values=('male', 'female'), ... required=False) ... ... age = zope.schema.Int( ... title=u'Age', ... description=u"The person's age.", ... min=0, ... default=20, ... required=False) ... ... @zope.interface.invariant ... def ensureIdAndNameNotEqual(person): ... if person.id == person.name: ... raise zope.interface.Invalid( ... "The id and name cannot be the same.") >>> from zope.schema.fieldproperty import FieldProperty >>> @zope.interface.implementer(IPerson) ... class Person(object): ... id = FieldProperty(IPerson['id']) ... name = FieldProperty(IPerson['name']) ... gender = FieldProperty(IPerson['gender']) ... age = FieldProperty(IPerson['age']) ... ... def __init__(self, id, name, gender=None, age=None): ... self.id = id ... self.name = name ... if gender: ... self.gender = gender ... if age: ... self.age = age ... ... def __repr__(self): ... return '<%s %r>' % (self.__class__.__name__, self.name) Okay, that should suffice for now. What's next? Well, first things first. Let's create an add form for the person. Since practice showed that the ``IAdding`` interface is overkill for most projects, the default add form of ``z3c.form`` requires you to define the creation and adding mechanism. **Note**: If it is not done, ``NotImplementedError[s]`` are raised: >>> from z3c.form.testing import TestRequest >>> from z3c.form import form, field >>> abstract = form.AddForm(None, TestRequest()) >>> abstract.create({}) Traceback (most recent call last): ... NotImplementedError >>> abstract.add(1) Traceback (most recent call last): ... NotImplementedError >>> abstract.nextURL() Traceback (most recent call last): ... NotImplementedError Thus let's now create a working add form: >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson) ... ... def create(self, data): ... return Person(**data) ... ... def add(self, object): ... self.context[object.id] = object ... ... def nextURL(self): ... return 'index.html' This is as simple as it gets. We explicitly define the pieces that are custom to every situation and let the default setup of the framework do the rest. This is intentionally similar to ``zope.formlib``, because we really like the simplicity of ``zope.formlib``'s way of dealing with the common use cases. Let's try to add a new person object to the root folder (which was created during test setup). For this add form, of course, the context is now the root folder: >>> request = TestRequest() >>> addForm = PersonAddForm(root, request) Since forms are not necessarily pages -- in fact often they are not -- they must not have a ``__call__`` method that does all the processing and rendering at once. Instead, we use the update/render pattern. Thus, we first call the ``update()`` method. >>> addForm.update() Actually a lot of things happen during this stage. Let us step through it one by one pointing out the effects. Find a widget manager and update it ----------------------------------- The default widget manager knows to look for the ``fields`` attribute in the form, since it implements ``IFieldsForm``: >>> from z3c.form import interfaces >>> interfaces.IFieldsForm.providedBy(addForm) True The widget manager is then stored in the ``widgets`` attribute as promised by the ``IForm`` interface: >>> addForm.widgets <z3c.form.field.FieldWidgets object at ...> The widget manager will have four widgets, one for each field: >>> addForm.widgets.keys() ['id', 'name', 'gender', 'age'] When the widget manager updates itself, several sub-tasks are processed. The manager goes through each field, trying to create a fully representative widget for the field. Field Availability ~~~~~~~~~~~~~~~~~~ Just because a field is requested in the field manager, does not mean that a widget has to be created for the field. There are cases when a field declaration might be ignored. The following reasons come to mind: * No widget is created if the data are not accessible in the content. * A custom widget manager has been registered to specifically ignore a field. In our simple example, all fields will be converted to widgets. Widget Creation ~~~~~~~~~~~~~~~ During the widget creation process, several pieces of information are transferred from the field to the widget: >>> age = addForm.widgets['age'] # field.title -> age.label >>> age.label u'Age' # field.required -> age.required >>> age.required False All these values can be overridden at later stages of the updating process. Widget Value ~~~~~~~~~~~~ The next step is to determine the value that should be displayed by the widget. This value could come from three places (looked up in this order): 1. The field's default value. 2. The content object that the form is representing. 3. The request in case a form has not been submitted or an error occurred. Since we are currently building an add form and not an edit form, there is no content object to represent, so the second step is not applicable. The third step is also not applicable as we do not have anything in the request. Therefore, the value should be the field's default value, or be empty. In this case the field provides a default value: >>> age.value u'20' While the default of the age field is actually the integer ``20``, the widget has converted the value to the output-ready string ``'20'`` using a data converter. Widget Mode ~~~~~~~~~~~ Now the widget manager looks at the field to determine the widget mode -- in other words whether the widget is a display or edit widget. In this case all fields are input fields: >>> age.mode 'input' Deciding which mode to use, however, might not be a trivial operation. It might depend on several factors (items listed later override earlier ones): * The global ``mode`` flag of the widget manager * The permission to the content's data value * The ``readonly`` flag in the schema field * The ``mode`` flag in the field Widget Attribute Values ~~~~~~~~~~~~~~~~~~~~~~~ As mentioned before, several widget attributes are optionally overridden when the widget updates itself: * label * required * mode Since we have no customization components registered, all of those fields will remain as set before. Find an action manager, update and execute it --------------------------------------------- After all widgets have been instantiated and the ``update()`` method has been called successfully, the actions are set up. By default, the form machinery uses the button declaration on the form to create its actions. For the add form, an add button is defined by default, so that we did not need to create our own. Thus, there should be one action: >>> len(addForm.actions) 1 The add button is an action and a widget at the same time: >>> addAction = addForm.actions['add'] >>> addAction.title u'Add' >>> addAction.value u'Add' After everything is set up, all pressed buttons are executed. Once a submitted action is detected, a special action handler adapter is used to determine the actions to take. Since the add button has not been pressed yet, no action occurred. Rendering the form ------------------ Once the update is complete we can render the form. Since we have not specified a template yet, we have to do this now. We have prepared a small and very simple template as part of this example: >>> import os >>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import tests >>> def addTemplate(form): ... form.template = BoundPageTemplate( ... ViewPageTemplateFile( ... 'simple_edit.pt', os.path.dirname(tests.__file__)), form) >>> addTemplate(addForm) Let's now render the page: >>> print(addForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">no value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> The update()/render() cycle is what happens when the form is called, i.e. when it is published: >>> print(addForm()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">no value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Note that we don't actually call render if the response has been set to a 3xx type status code (e.g. a redirect or not modified response), since the browser would not render it anyway: >>> request.response.setStatus(304) >>> print(addForm()) Let's go back to a normal status to continue the test. >>> request.response.setStatus(200) Submitting an add form successfully ----------------------------------- Initially the root folder of the application is empty: >>> sorted(root) [] Let's now fill the request with all the right values so that upon submitting the form with the "Add" button, the person should be added to the root folder: >>> request = TestRequest(form={ ... 'form.widgets.id': u'srichter', ... 'form.widgets.name': u'Stephan Richter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': u'20', ... 'form.buttons.add': u'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> sorted(root) [u'srichter'] >>> stephan = root[u'srichter'] >>> stephan.id u'srichter' >>> stephan.name u'Stephan Richter' >>> stephan.gender 'male' >>> stephan.age 20 Submitting an add form with invalid data ---------------------------------------- Next we try to submit the add form with the required name missing. Thus, the add form should not complete with the addition, but return with the add form pointing out the error. >>> request = TestRequest(form={ ... 'form.widgets.id': u'srichter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': u'23', ... 'form.buttons.add': u'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() The widget manager and the widget causing the error should have an error message: >>> [(error.widget.__name__, error) for error in addForm.widgets.errors] [('name', <ErrorViewSnippet for RequiredMissing>)] >>> addForm.widgets['name'].error <ErrorViewSnippet for RequiredMissing> Let's now render the form: >>> addTemplate(addForm) >>> print(addForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> Name: <div class="error">Required input is missing.</div> </li> </ul> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="srichter" /> </div> <div class="row"> <b><div class="error">Required input is missing.</div> </b><label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">no value</option> <option id="form-widgets-gender-0" value="male" selected="selected">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="23" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Note that the values of the field are now extracted from the request. Another way to receive an error is by not fulfilling the invariants of the schema. In our case, the id and name cannot be the same. So let's provoke the error now: >>> request = TestRequest(form={ ... 'form.widgets.id': u'Stephan', ... 'form.widgets.name': u'Stephan', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': u'23', ... 'form.buttons.add': u'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addTemplate(addForm) >>> addForm.update() and see how the form looks like: >>> print(addForm.render() # doctest: +NOPARSE_MARKUP) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> <div class="error">The id and name cannot be the same.</div> </li> </ul> ... </body> </html> Let's try to provide a negative age, which is not possible either: >>> request = TestRequest(form={ ... 'form.widgets.id': u'srichter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': u'-5', ... 'form.buttons.add': u'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> [(view.widget.label, view) for view in addForm.widgets.errors] [(u'Name', <ErrorViewSnippet for RequiredMissing>), (u'Age', <ErrorViewSnippet for TooSmall>)] But the error message for a negative age is too generic: >>> print(addForm.widgets['age'].error.render()) <div class="error">Value is too small</div> It would be better to say that negative values are disallowed. So let's register a new error view snippet for the ``TooSmall`` error: >>> from z3c.form import error >>> class TooSmallView(error.ErrorViewSnippet): ... zope.component.adapts( ... zope.schema.interfaces.TooSmall, None, None, None, None, None) ... ... def update(self): ... super(TooSmallView, self).update() ... if self.field.min == 0: ... self.message = u'The value cannot be a negative number.' >>> zope.component.provideAdapter(TooSmallView) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> print(addForm.widgets['age'].error.render()) <div class="error">The value cannot be a negative number.</div> Note: The ``adapts()`` declaration might look strange. An error view snippet is actually a multiadapter that adapts a combination of 6 objects -- error, request, widget, field, form, content. By specifying only the error, we tell the system that we do not care about the other discriminators, which then can be anything. We could also have used ``zope.interface.Interface`` instead, which would be equivalent. Additional Form Attributes and API ---------------------------------- Since we are talking about HTML forms here, add and edit forms support all relevant FORM element attributes as attributes on the class. >>> addForm.method 'post' >>> addForm.enctype 'multipart/form-data' >>> addForm.acceptCharset >>> addForm.accept The ``action`` attribute is computed. By default it is the current URL: >>> addForm.action 'http://127.0.0.1' The name is also computed. By default it takes the prefix and removes any trailing ".". >>> addForm.name 'form' The id is computed from the name, replacing dots with hyphens. Let's set the prefix to something containing more than one final dot and check how it works. >>> addForm.prefix = 'person.form.add.' >>> addForm.id 'person-form-add' The template can then use those attributes, if it likes to. In the examples previously we set the template manually. If no template is specified, the system tries to find an adapter. Without any special configuration, there is no adapter, so rendering the form fails: >>> addForm.template = None >>> addForm.render() Traceback (most recent call last): ... ComponentLookupError: ((...), <InterfaceClass ...IPageTemplate>, u'') The form module provides a simple component to create adapter factories from templates: >>> factory = form.FormTemplateFactory( ... testing.getPath('../tests/simple_edit.pt'), form=PersonAddForm) Let's register our new template-based adapter factory: >>> zope.component.provideAdapter(factory) Now the factory will be used to provide a template: >>> print(addForm.render() # doctest: +NOPARSE_MARKUP) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... </html> Since a form can also be used as a page itself, it is callable. When you call it will invoke both the ``update()`` and ``render()`` methods: >>> print(addForm() # doctest: +NOPARSE_MARKUP) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... </html> The form also provides a label for rendering a required info. This required info depends by default on the given requiredInfo label and if at least one field is required: >>> addForm.requiredInfo u'<span class="required">*</span>&ndash; required' If we set the labelRequired to None, we do not get a requiredInfo label: >>> addForm.labelRequired = None >>> addForm.requiredInfo is None True Changing Widget Attribute Values -------------------------------- It frequently happens that a customer comes along and wants to slightly or totally change some of the text shown in forms or make optional fields required. It does not make sense to always have to adjust the schema or implement a custom schema for these use cases. With the z3c.form framework all attributes -- for which it is sensible to replace a value without touching the code -- are customizable via an attribute value adapter. To demonstrate this feature, let's change the label of the name widget from "Name" to "Full Name": >>> from z3c.form import widget >>> NameLabel = widget.StaticWidgetAttribute( ... u'Full Name', field=IPerson['name']) >>> zope.component.provideAdapter(NameLabel, name='label') When the form renders, the label has now changed: >>> addForm = PersonAddForm(root, TestRequest()) >>> addTemplate(addForm) >>> addForm.update() >>> print(testing.render(addForm, './/xmlns:div[2][@class="row"]')) <div class="row"> <label for="form-widgets-name">Full Name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value=""> </div> Adding a "Cancel" button ------------------------ Let's say a client requests that all add forms should have a "Cancel" button. When the button is pressed, the user is forwarded to the next URL of the add form. As always, the goal is to not touch the core implementation of the code, but make those changes externally. Adding a button/action is a little bit more involved than changing a value, because you have to insert the additional action and customize the action handler. Based on your needs of flexibility, multiple approaches could be chosen. Here we demonstrate the simplest one. The first step is to create a custom action manager that always inserts a cancel action: >>> from z3c.form import button >>> class AddActions(button.ButtonActions): ... zope.component.adapts( ... interfaces.IAddForm, ... zope.interface.Interface, ... zope.interface.Interface) ... ... def update(self): ... self.form.buttons = button.Buttons( ... self.form.buttons, ... button.Button('cancel', u'Cancel')) ... super(AddActions, self).update() After registering the new action manager, >>> zope.component.provideAdapter(AddActions) the add form should display a cancel button: >>> addForm.update() >>> print(testing.render(addForm, './/xmlns:div[@class="action"]')) <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> <div class="action"> <input type="submit" id="form-buttons-cancel" name="form.buttons.cancel" class="submit-widget button-field" value="Cancel" /> </div> But showing the button does not mean it does anything. So we also need a custom action handler to handle the cancel action: >>> class AddActionHandler(button.ButtonActionHandler): ... zope.component.adapts( ... interfaces.IAddForm, ... zope.interface.Interface, ... zope.interface.Interface, ... button.ButtonAction) ... ... def __call__(self): ... if self.action.name == 'form.buttons.cancel': ... self.form._finishedAdd = True ... return ... super(AddActionHandler, self).__call__() After registering the action handler, >>> zope.component.provideAdapter(AddActionHandler) we can press the cancel button and we will be forwarded: >>> request = TestRequest(form={'form.buttons.cancel': u'Cancel'}) >>> addForm = PersonAddForm(root, request) >>> addTemplate(addForm) >>> addForm.update() >>> addForm.render() '' >>> request.response.getStatus() 302 >>> request.response.getHeader('Location') 'index.html' Eventually, we might have action managers and handlers that are much more powerful and some of the manual labor in this example would become unnecessary. Creating an Edit Form --------------------- Now that we have exhaustively covered the customization possibilities of add forms, let's create an edit form. Edit forms are even simpler than add forms, since all actions are completely automatic: >>> class PersonEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) We can use the created person from the successful addition above. >>> editForm = PersonEditForm(root[u'srichter'], TestRequest()) After adding a template, we can look at the form: >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget required textline-field">srichter</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">no value</option> <option id="form-widgets-gender-0" value="male" selected="selected">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> As you can see, the data are being pulled in from the context for the edit form. Next we will look at the behavior when submitting the form. Failure Upon Submission of Edit Form ------------------------------------ Let's now submit the form having some invalid data. >>> request = TestRequest(form={ ... 'form.widgets.name': u'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': u'-1', ... 'form.buttons.apply': u'Apply'} ... ) >>> editForm = PersonEditForm(root[u'srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> Age: <div class="error">The value cannot be a negative number.</div> </li> </ul> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget required textline-field">srichter</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Claudia Richter" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">no value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female" selected="selected">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <b><div class="error">The value cannot be a negative number.</div> </b><label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="-1" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Successfully Editing Content ---------------------------- Let's now resubmit the form with valid data, so the data should be updated. >>> request = TestRequest(form={ ... 'form.widgets.name': u'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': u'27', ... 'form.buttons.apply': u'Apply'} ... ) >>> editForm = PersonEditForm(root[u'srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) <i>Data successfully updated.</i> >>> stephan = root[u'srichter'] >>> stephan.name u'Claudia Richter' >>> stephan.gender 'female' >>> stephan.age 27 When an edit form is successfully committed, a detailed object-modified event is sent out telling the system about the changes. To see the error, let's create an event subscriber for object-modified events: >>> eventlog = [] >>> import zope.lifecycleevent >>> @zope.component.adapter(zope.lifecycleevent.ObjectModifiedEvent) ... def logEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent) Let's now submit the form again, successfully changing the age: >>> request = TestRequest(form={ ... 'form.widgets.name': u'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': u'29', ... 'form.buttons.apply': u'Apply'} ... ) >>> editForm = PersonEditForm(root[u'srichter'], request) >>> addTemplate(editForm) >>> editForm.update() We can now look at the event: >>> event = eventlog[-1] >>> event <zope...ObjectModifiedEvent object at ...> >>> attrs = event.descriptions[0] >>> attrs.interface <InterfaceClass __builtin__.IPerson> >>> attrs.attributes ('age',) Successful Action with No Changes --------------------------------- When submitting the form without any changes, the form will tell you so. >>> request = TestRequest(form={ ... 'form.widgets.name': u'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': u'29', ... 'form.buttons.apply': u'Apply'} ... ) >>> editForm = PersonEditForm(root[u'srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) <i>No changes were applied.</i> Changing Status Messages ------------------------ Depending on the project, it is often desirable to change the status messages to fit the application. In ``zope.formlib`` this was hard to do, since the messages were buried within fairly complex methods that one did not want to touch. In this package all those messages are exposed as form attributes. There are three messages for the edit form: * ``formErrorsMessage`` -- Indicates that an error occurred while applying the changes. This message is also available for the add form. * ``successMessage`` -- The form data was successfully applied. * ``noChangesMessage`` -- No changes were found in the form data. Let's now change the ``noChangesMessage``: >>> editForm.noChangesMessage = u'No changes were detected in the form data.' >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) <i>No changes were detected in the form data.</i> When even more flexibility is required within a project, one could also implement these messages as properties looking up an attribute value. However, we have found this to be a rare case. Creating Edit Forms for Dictionaries ------------------------------------ Sometimes it is not desirable to edit a class instance that implements the fields, but other types of object. A good example is the need to modify a simple dictionary, where the field names are the keys. To do that, a special data manager for dictionaries is available: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.DictionaryField) The only step the developer has to complete is to re-implement the form's ``getContent()`` method to return the dictionary: >>> personDict = {'id': u'rineichen', 'name': u'Roger Ineichen', ... 'gender': None, 'age': None} >>> class PersonDictEditForm(PersonEditForm): ... def getContent(self): ... return personDict We can now use the form as usual: >>> editForm = PersonDictEditForm(None, TestRequest()) >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget required textline-field">rineichen</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Roger Ineichen" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--" selected="selected">no value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Note that the name displayed in the form is identical to the one in the dictionary. Let's now submit a form to ensure that the data are also written to the dictionary: >>> request = TestRequest(form={ ... 'form.widgets.name': u'Jesse Ineichen', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': u'5', ... 'form.buttons.apply': u'Apply'} ... ) >>> editForm = PersonDictEditForm(None, request) >>> editForm.update() >>> len(personDict) 4 >>> personDict['age'] 5 >>> personDict['gender'] 'male' >>> personDict['id'] u'rineichen' >>> personDict['name'] u'Jesse Ineichen' Creating a Display Form ----------------------- Creating a display form is simple; just instantiate, update and render it: >>> class PersonDisplayForm(form.DisplayForm): ... fields = field.Fields(IPerson) ... template = ViewPageTemplateFile( ... 'simple_display.pt', os.path.dirname(tests.__file__)) >>> display = PersonDisplayForm(stephan, TestRequest()) >>> display.update() >>> print(display.render()) Traceback (most recent call last): ... KeyError: '__conform__' <BLANKLINE> - Expression: "repeat/value/end" - Filename: ...select_display.pt - Location: (23:32) <BLANKLINE> - Source: ... tal:block condition="not:repeat/value/end">, </tal:block ... Simple Form Customization ------------------------- The form exposes several of the widget manager's attributes as attributes on the form. They are: ``mode``, ``ignoreContext``, ``ignoreRequest``, and ``ignoreReadonly``. Here are the values for the display form we just created: >>> display.mode 'display' >>> display.ignoreContext False >>> display.ignoreRequest True >>> display.ignoreReadonly False These values should be equal to the ones of the widget manager: >>> display.widgets.mode 'display' >>> display.widgets.ignoreContext False >>> display.widgets.ignoreRequest True >>> display.widgets.ignoreReadonly False Now, if we change those values before updating the widgets, ... >>> display.mode = interfaces.INPUT_MODE >>> display.ignoreContext = True >>> display.ignoreRequest = False >>> display.ignoreReadonly = True ... the widget manager will have the same values after updating the widgets: >>> display.updateWidgets() >>> display.widgets.mode 'input' >>> display.widgets.ignoreContext True >>> display.widgets.ignoreRequest False >>> display.widgets.ignoreReadonly True Extending Forms --------------- One very common use case is to extend forms. For example, you would like to use the edit form and its defined "Apply" button, but add another button yourself. Unfortunately, just inheriting the form is not enough, because the new button and handler declarations will override the inherited ones. Let me demonstrate the problem: >>> class BaseForm(form.Form): ... fields = field.Fields(IPerson).select('name') ... ... @button.buttonAndHandler(u'Apply') ... def handleApply(self, action): ... print('success') >>> BaseForm.fields.keys() ['name'] >>> BaseForm.buttons.keys() ['apply'] >>> BaseForm.handlers <Handlers [<Handler for <Button 'apply' u'Apply'>>]> Let's now derive a form from the base form: >>> class DerivedForm(BaseForm): ... fields = field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler(u'Cancel') ... def handleCancel(self, action): ... print('cancel') >>> DerivedForm.fields.keys() ['gender'] >>> DerivedForm.buttons.keys() ['cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'cancel' u'Cancel'>>]> The obvious method to "inherit" the base form's information is to copy it over: >>> class DerivedForm(BaseForm): ... fields = BaseForm.fields.copy() ... buttons = BaseForm.buttons.copy() ... handlers = BaseForm.handlers.copy() ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler(u'Cancel') ... def handleCancel(self, action): ... print('cancel') >>> DerivedForm.fields.keys() ['name', 'gender'] >>> DerivedForm.buttons.keys() ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' u'Apply'>>, <Handler for <Button 'cancel' u'Cancel'>>]> But this is pretty clumsy. Instead, the ``form`` module provides a helper method that will do the extending for you: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler(u'Cancel') ... def handleCancel(self, action): ... print('cancel') >>> DerivedForm.fields.keys() ['name', 'gender'] >>> DerivedForm.buttons.keys() ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' u'Apply'>>, <Handler for <Button 'cancel' u'Cancel'>>]> If you, for example do not want to extend the buttons, you can turn that off: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm, ignoreButtons=True) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler(u'Cancel') ... def handleCancel(self, action): ... print('cancel') >>> DerivedForm.fields.keys() ['name', 'gender'] >>> DerivedForm.buttons.keys() ['cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' u'Apply'>>, <Handler for <Button 'cancel' u'Cancel'>>]> If you, for example do not want to extend the handlers, you can turn that off: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm, ignoreHandlers=True) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler(u'Cancel') ... def handleCancel(self, action): ... print('cancel') >>> DerivedForm.fields.keys() ['name', 'gender'] >>> DerivedForm.buttons.keys() ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'cancel' u'Cancel'>>]> Custom widget factories ----------------------- Another important part of a form is that we can use custom widgets. We can do this in a form by defining a widget factory for a field. We can get the field from the fields collection e.g. ``fields['foo']``. This means, we can define new widget factories by defining ``fields['foo'].widgetFactory = MyWidget``. Let's show a sample and define a custom widget: >>> from z3c.form.browser import text >>> class MyWidget(text.TextWidget): ... """My new widget.""" ... klass = u'MyCSS' Now we can define a field widget factory: >>> def MyFieldWidget(field, request): ... """IFieldWidget factory for MyWidget.""" ... return widget.FieldWidget(field, MyWidget(request)) We register the ``MyWidget`` in a form like: >>> class MyEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) ... fields['name'].widgetFactory = MyFieldWidget We can see that the custom widget gets used in the rendered form: >>> myEdit = MyEditForm(root[u'srichter'], TestRequest()) >>> addTemplate(myEdit) >>> myEdit.update() >>> print(testing.render(myEdit, './/xmlns:input[@id="form-widgets-name"]')) <input type="text" id="form-widgets-name" name="form.widgets.name" class="MyCSS required textline-field" value="Claudia Richter" /> Hidden fields ------------- Another important part of a form is that we can generate hidden widgets. We can do this in a form by defining a widget mode. We can do this by override the setUpWidgets method. >>> class HiddenFieldEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) ... fields['name'].widgetFactory = MyFieldWidget ... ... def updateWidgets(self): ... super(HiddenFieldEditForm, self).updateWidgets() ... self.widgets['age'].mode = interfaces.HIDDEN_MODE We can see that the widget gets rendered as hidden: >>> hiddenEdit = HiddenFieldEditForm(root[u'srichter'], TestRequest()) >>> addTemplate(hiddenEdit) >>> hiddenEdit.update() >>> print(testing.render(hiddenEdit, './/xmlns:input[@id="form-widgets-age"]')) <input type="hidden" id="form-widgets-age" name="form.widgets.age" class="hidden-widget" value="29" /> Actions with Errors ------------------- Even though the data might be validated correctly, it sometimes happens that data turns out to be invalid while the action is executed. In those cases a special action execution error can be raised that wraps the original error. >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson).select('id') ... ... @button.buttonAndHandler(u'Check') ... def handleCheck(self, action): ... data, errors = self.extractData() ... if data['id'] in self.getContent(): ... raise interfaces.WidgetActionExecutionError( ... 'id', zope.interface.Invalid('Id already exists')) In this case the action execution error is specific to a widget. The framework will attach a proper error view to the widget and the widget manager: >>> request = TestRequest(form={ ... 'form.widgets.id': u'srichter', ... 'form.buttons.check': u'Check'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> addForm.widgets.errors (<InvalidErrorViewSnippet for Invalid>,) >>> addForm.widgets['id'].error <InvalidErrorViewSnippet for Invalid> >>> addForm.status u'There were some errors.' If the error is non-widget specific, then we can simply use the generic action execution error: >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson).select('id') ... ... @button.buttonAndHandler(u'Check') ... def handleCheck(self, action): ... raise interfaces.ActionExecutionError( ... zope.interface.Invalid('Some problem occurred.')) Let's have a look at the result: >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> addForm.widgets.errors (<InvalidErrorViewSnippet for Invalid>,) >>> addForm.status u'There were some errors.' **Note**: The action execution errors are connected to the form via an event listener called ``handlerActionError``. This event listener listens for ``IActionErrorEvent`` events. If the event is called for an action associated with a form, the listener does its work as seen above. If the action is not coupled to a form, then event listener does nothing: >>> from z3c.form import action >>> cancel = action.Action(request, u'Cancel') >>> event = action.ActionErrorOccurred(cancel, ValueError(3)) >>> form.handleActionError(event) Applying Changes ---------------- When applying the data of a form to a content component, the function ``applyChanges()`` is called. It simply iterates through the fields of the form and uses the data managers to store the values. The output of the function is a list of changes: >>> roger = Person(u'roger', u'Roger') >>> roger <Person u'Roger'> >>> class BaseForm(form.Form): ... fields = field.Fields(IPerson).select('name') >>> myForm = BaseForm(roger, TestRequest()) >>> form.applyChanges(myForm, roger, {'name': u'Roger Ineichen'}) {<InterfaceClass __builtin__.IPerson>: ['name']} >>> roger <Person u'Roger Ineichen'> When a field is missing from the data, it is simply skipped: >>> form.applyChanges(myForm, roger, {}) {} If the new and old value are identical, storing the data is skipped as well: >>> form.applyChanges(myForm, roger, {'name': u'Roger Ineichen'}) {} In some cases the data converter for a field-widget pair returns the ``NOT_CHANGED`` value. In this case, the field is skipped as well: >>> form.applyChanges(myForm, roger, {'name': interfaces.NOT_CHANGED}) {} >>> roger <Person u'Roger Ineichen'> Refreshing actions ------------------ Sometimes, it's useful to update actions again after executing them, because some conditions could have changed. For example, imagine we have a sequence edit form that has a delete button. We don't want to show delete button when the sequence is empty. The button condition would handle this, but what if the sequence becomes empty as a result of execution of the delete action that was available? In that case we want to refresh our actions to new conditions to make our delete button not visible anymore. The ``refreshActions`` form variable is intended to handle this case. Let's create a simple form with an action that clears our context sequence. >>> class SequenceForm(form.Form): ... ... @button.buttonAndHandler(u'Empty', condition=lambda form:bool(form.context)) ... def handleEmpty(self, action): ... self.context[:] = [] ... self.refreshActions = True First, let's illustrate simple cases, when no button is pressed. The button will be available when context is not empty. >>> context = [1, 2, 3, 4] >>> request = TestRequest() >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:div[@class="action"]')) <div class="action"> <input type="submit" id="form-buttons-empty" name="form.buttons.empty" class="submit-widget button-field" value="Empty" /> </div> The button will not be available when the context is empty. >>> context = [] >>> request = TestRequest() >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:form')) <form action="."> </form> Now, the most interesting case when context is not empty, but becomes empty as a result of pressing the "empty" button. We set the ``refreshActions`` flag in the action handler, so our actions should be updated to new conditions. >>> context = [1, 2, 3, 4, 5] >>> request = TestRequest(form={ ... 'form.buttons.empty': u'Empty'} ... ) >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:form')) <form action="."> </form> Integration tests ----------------- Identifying the different forms can be important if it comes to layout template lookup. Let's ensure that we support the right interfaces for the different forms. Form ~~~~ >>> from zope.interface.verify import verifyObject >>> from z3c.form import interfaces >>> obj = form.Form(None, None) >>> verifyObject(interfaces.IForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False DisplayForm ~~~~~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.DisplayForm(None, None) >>> verifyObject(interfaces.IDisplayForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False EditForm ~~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.EditForm(None, None) >>> verifyObject(interfaces.IEditForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False AddForm ~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.AddForm(None, None) >>> verifyObject(interfaces.IAddForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) True
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/form-chameleon-issue-repeat-addons.rst
form-chameleon-issue-repeat-addons.rst
========== Validators ========== Validators are components that validate submitted data. This is certainly not a new concept, but in the previous form frameworks validation was hidden in many places: * Field/Widget Validation The schema field consists of a ``validate()`` method. Validation is automatically invoked when converting a unicode string to a field value using ``fromUnicode()``. This makes it very hard to customize the field validation. No hooks were provided to exert additional restriction at the presentation level. * Schema/Form Validation This type of validation was not supported at all initially. ``zope.formlib`` fixed this problem by validating against schema invariants. While this was a first good step, it still made it hard to customize validators, since it required touching the base implementations of the forms. * Action Validation ``zope.formlib`` supports the notion of action validators. Actions have a success and failure handler. If the validation succeeds, the success handler is called, otherwise the failure handler is chosen. We believe that this design was ill-conceived, especially the default, which required the data to completely validate in order for the action to successful. There are many actions that do not even care about the data in the form, such as "Help", "Cancel" and "Reset" buttons. Thus, validation should be part of the data retrieval process and not the action. For me, the primary goals of the validator framework are as follows: * Assert additional restrictions on the data at the presentation level. There are several use cases for this. Sometimes clients desire additional restrictions on data for their particular version of the software. It is not always desirable to adjust the model for this client, since the framework knows how to handle the less restrictive case anyways. In another case, additional restrictions might be applied to a particular form due to limited restrictions. * Make validation pluggable. Like most other components of this package, it should be possible to control the validation adapters at a fine grained level. * Widgets: context, request, view, field[1], widget * Widget Managers: context, request, view, schema[2], manager [1].. This is optional, since widgets must not necessarily have fields. [2].. This is optional, since widget managers must not necessarily have manage field widgets and thus know about schemas. * Provide good defaults that behave sensibly. Good defaults are, like in anywhere in this package, very important. We have chosen to implement the ``zope.formlib`` behavior as the default, since it worked very well -- with exception of action validation, of course. For this package, we have decided to support validators at the widget and widget manager level. By default, the framework only supports field widgets, since the validation of field-absent widgets is generally not well-defined. Thus, we first need to create a schema. >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... login = zope.schema.TextLine( ... title=u'Login', ... min_length=1, ... max_length=10, ... required=True) ... ... email = zope.schema.TextLine( ... title=u'E-mail') ... ... @zope.interface.invariant ... def isLoginPartOfEmail(person): ... if not person.email.startswith(person.login): ... raise zope.interface.Invalid("The login not part of email.") >>> @zope.interface.implementer(IPerson) ... class Person(object): ... login = None ... email = None Widget Validators ----------------- Widget validators only validate the data of one particular widget. The validated value is always assumed to be an internal value and not a widget value. By default, the system uses the simple field validator, which simply uses the ``validate()`` method of the field. For instantiation, all validators have the following signature for its discriminators: context, request, view, field, and widget >>> from z3c.form import validator >>> simple = validator.SimpleFieldValidator( ... None, None, None, IPerson['login'], None) A validator has a single method ``validate()``. When the validation is successful, ``None`` is returned: >>> simple.validate(u'srichter') A validation error is raised, when the validation fails: >>> simple.validate(u'StephanCaveman3') Traceback (most recent call last): ... TooLong: (u'StephanCaveman3', 10) Let's now create a validator that also requires at least 1 numerical character in the login name: >>> import re >>> class LoginValidator(validator.SimpleFieldValidator): ... ... def validate(self, value): ... super(LoginValidator, self).validate(value) ... if re.search('[0-9]', value) is None: ... raise zope.interface.Invalid('No numerical character found.') Let's now try our new validator: >>> login = LoginValidator(None, None, None, IPerson['login'], None) >>> login.validate(u'srichter1') >>> login.validate(u'srichter') Traceback (most recent call last): ... Invalid: No numerical character found. We can now register the validator with the component architecture, ... >>> import zope.component >>> zope.component.provideAdapter(LoginValidator) and look up the adapter using the usual way: >>> from z3c.form import interfaces >>> zope.component.queryMultiAdapter( ... (None, None, None, IPerson['login'], None), ... interfaces.IValidator) <LoginValidator for IPerson['login']> Unfortunately, the adapter is now registered for all fields, so that the E-mail field also has this restriction (which is okay in this case, but not generally): >>> zope.component.queryMultiAdapter( ... (None, None, None, IPerson['email'], None), ... interfaces.IValidator) <LoginValidator for IPerson['email']> The validator module provides a helper function to set the discriminators for a validator, which can include instances: >>> validator.WidgetValidatorDiscriminators( ... LoginValidator, field=IPerson['login']) Let's now clean up the component architecture and register the login validator again: >>> from zope.testing import cleanup >>> cleanup.cleanUp() >>> zope.component.provideAdapter(LoginValidator) >>> zope.component.queryMultiAdapter( ... (None, None, None, IPerson['login'], None), ... interfaces.IValidator) <LoginValidator for IPerson['login']> >>> zope.component.queryMultiAdapter( ... (None, None, None, IPerson['email'], None), ... interfaces.IValidator) Ignoring unchanged values ~~~~~~~~~~~~~~~~~~~~~~~~~ Most of the time we want to ignore unchanged fields/values at validation. A common usecase for this is if a value went away from a vocabulary and we want to keep the old value after editing. In case you want to strict behaviour, register ``StrictSimpleFieldValidator`` for your layer. >>> simple = validator.SimpleFieldValidator( ... None, None, None, IPerson['login'], None) NOT_CHANGED never gets validated. >>> simple.validate(interfaces.NOT_CHANGED) Current value gets extracted by ``IDataManager`` via the widget, field and context >>> from z3c.form.datamanager import AttributeField >>> zope.component.provideAdapter(AttributeField) >>> import z3c.form.testing >>> request = z3c.form.testing.TestRequest() >>> import z3c.form.widget >>> widget = z3c.form.widget.Widget(request) >>> context = Person() >>> widget.context = context >>> from z3c.form import interfaces >>> zope.interface.alsoProvides(widget, interfaces.IContextAware) >>> simple = validator.SimpleFieldValidator( ... context, request, None, IPerson['login'], widget) OK, let's see checking after setup. Works like a StrictSimpleFieldValidator until we have to validate a different value: >>> context.login = u'john' >>> simple.validate(u'carter') >>> simple.validate(u'hippocratiusxy') Traceback (most recent call last): ... TooLong: (u'hippocratiusxy', 10) Validating the unchanged value works despite it would be an error. >>> context.login = u'hippocratiusxy' >>> simple.validate(u'hippocratiusxy') Unless we want to force validation: >>> simple.validate(u'hippocratiusxy', force=True) Traceback (most recent call last): ... TooLong: (u'hippocratiusxy', 10) Some exceptions: ``missing_value`` gets validated >>> simple.validate(IPerson['login'].missing_value) Traceback (most recent call last): ... RequiredMissing: login Widget Validators and File-Uploads ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ File-Uploads behave a bit different than the other form elements. Whether the user did not choose a file to upload ``interfaces.NOT_CHANGED`` is set as value. But the validator knows how to handle this. The example has two bytes fields where File-Uploads are possible, one field is required the other one not: >>> class IPhoto(zope.interface.Interface): ... data = zope.schema.Bytes( ... title=u'Photo', ... required=True) ... ... thumb = zope.schema.Bytes( ... title=u'Thumbnail', ... required=False) There are several possible cases to differentiate between: No widget +++++++++ If there is no widget or the widget does not provide ``interfaces.IContextAware``, no value is looked up from the context. So the not required field validates successfully but the required one has a required missing error, as the default value of the field is looked up on the field: >>> simple_thumb = validator.StrictSimpleFieldValidator( ... None, None, None, IPhoto['thumb'], None) >>> simple_thumb.validate(interfaces.NOT_CHANGED) >>> simple_data = validator.StrictSimpleFieldValidator( ... None, None, None, IPhoto['data'], None) >>> simple_data.validate(interfaces.NOT_CHANGED) Traceback (most recent call last): RequiredMissing: data Widget which ignores context ++++++++++++++++++++++++++++ If the context is ignored in the widget - as in the add form - the behavior is the same as if there was no widget: >>> import z3c.form.widget >>> widget = z3c.form.widget.Widget(None) >>> zope.interface.alsoProvides(widget, interfaces.IContextAware) >>> widget.ignoreContext = True >>> simple_thumb = validator.StrictSimpleFieldValidator( ... None, None, None, IPhoto['thumb'], widget) >>> simple_thumb.validate(interfaces.NOT_CHANGED) >>> simple_data = validator.StrictSimpleFieldValidator( ... None, None, None, IPhoto['data'], widget) >>> simple_data.validate(interfaces.NOT_CHANGED) Traceback (most recent call last): RequiredMissing: data Look up value from default adapter ++++++++++++++++++++++++++++++++++ When the value is ``interfaces.NOT_CHANGED`` the validator tries to look up the default value using a ``interfaces.IValue`` adapter. Whether the adapter is found, its value is used as default, so the validation of the required field is successful here: >>> data_default = z3c.form.widget.StaticWidgetAttribute( ... b'data', context=None, request=None, view=None, ... field=IPhoto['data'], widget=widget) >>> zope.component.provideAdapter(data_default, name='default') >>> simple_data.validate(interfaces.NOT_CHANGED) Look up value from context ++++++++++++++++++++++++++ If there is a context aware widget which does not ignore its context, the value is looked up on the context using a data manager: >>> @zope.interface.implementer(IPhoto) ... class Photo(object): ... data = None ... thumb = None >>> photo = Photo() >>> widget.ignoreContext = False >>> zope.component.provideAdapter(z3c.form.datamanager.AttributeField) >>> simple_thumb = validator.StrictSimpleFieldValidator( ... photo, None, None, IPhoto['thumb'], widget) >>> simple_thumb.validate(interfaces.NOT_CHANGED) If the value is not set on the context it is a required missing as neither context nor input have a valid value: >>> simple_data = validator.StrictSimpleFieldValidator( ... photo, None, None, IPhoto['data'], widget) >>> simple_data.validate(interfaces.NOT_CHANGED) Traceback (most recent call last): RequiredMissing: data After setting the value validation is successful: >>> photo.data = b'data' >>> simple_data.validate(interfaces.NOT_CHANGED) Clean-up ++++++++ >>> gsm = zope.component.getGlobalSiteManager() >>> gsm.unregisterAdapter(z3c.form.datamanager.AttributeField) True >>> gsm.unregisterAdapter(data_default, name='default') True Ignoring required ~~~~~~~~~~~~~~~~~ Sometimes we want to ignore ``required`` checking. That's because we want to have *all* fields extracted from the form regardless whether required fields are filled. And have no required-errors displayed. >>> class IPersonRequired(zope.interface.Interface): ... login = zope.schema.TextLine( ... title=u'Login', ... required=True) ... ... email = zope.schema.TextLine( ... title=u'E-mail') >>> simple = validator.SimpleFieldValidator( ... None, None, None, IPersonRequired['login'], None) >>> simple.validate(None) Traceback (most recent call last): ... RequiredMissing: login Ooops we need a widget too. >>> widget = z3c.form.widget.Widget(None) >>> widget.field = IPersonRequired['login'] >>> simple = validator.SimpleFieldValidator( ... None, None, None, IPersonRequired['login'], widget) >>> simple.validate(None) Traceback (most recent call last): ... RequiredMissing: login Meeeh, need to signal that we need to ignore ``required``: >>> widget.ignoreRequiredOnValidation = True >>> simple.validate(None) Widget Manager Validators ------------------------- The widget manager validator, while similar in spirit, works somewhat different. The discriminators of the widget manager validator are: context, request, view, schema, and manager. A simple default implementation is provided that checks the invariants of the schemas: >>> invariants = validator.InvariantsValidator( ... None, None, None, IPerson, None) Widget manager validators have the option to validate a data dictionary, >>> invariants.validate( ... {'login': u'srichter', 'email': u'[email protected]'}) () or an object implementing the schema: >>> @zope.interface.implementer(IPerson) ... class Person(object): ... login = u'srichter' ... email = u'[email protected]' >>> stephan = Person() >>> invariants.validateObject(stephan) () Since multiple errors can occur during the validation process, all errors are collected in a tuple, which is returned. If the tuple is empty, the validation was successful. Let's now generate a failure: >>> errors = invariants.validate( ... {'login': u'srichter', 'email': u'[email protected]'}) >>> for e in errors: ... print(e.__class__.__name__ + ':', e) Invalid: The login not part of email. Let's now have a look at writing a custom validator. In this case, we want to ensure that the E-mail address is at most twice as long as the login: >>> class CustomValidator(validator.InvariantsValidator): ... def validateObject(self, obj): ... errors = super(CustomValidator, self).validateObject(obj) ... if len(obj.email) > 2 * len(obj.login): ... errors += (zope.interface.Invalid('Email too long.'),) ... return errors Since the ``validate()`` method of ``InvatiantsValidator`` simply uses ``validateObject()`` it is enough to only override ``validateObject()``. Now we can use the validator: >>> custom = CustomValidator( ... None, None, None, IPerson, None) >>> custom.validate( ... {'login': u'srichter', 'email': u'[email protected]'}) () >>> errors = custom.validate( ... {'login': u'srichter', 'email': u'[email protected]'}) >>> for e in errors: ... print(e.__class__.__name__ + ':', e) Invalid: Email too long. To register the custom validator only for this schema, we have to use the discriminator generator again. >>> from z3c.form import util >>> validator.WidgetsValidatorDiscriminators( ... CustomValidator, schema=util.getSpecification(IPerson, force=True)) Note: Of course we could have used the ``zope.component.adapts()`` function from within the class, but I think it is too tedious, since you have to specify all discriminators and not only the specific ones you are interested in. After registering the validator, >>> zope.component.provideAdapter(CustomValidator) it becomes the validator for this schema: >>> zope.component.queryMultiAdapter( ... (None, None, None, IPerson, None), interfaces.IManagerValidator) <CustomValidator for IPerson> >>> class ICar(zope.interface.Interface): ... pass >>> zope.component.queryMultiAdapter( ... (None, None, None, ICar, None), interfaces.IManagerValidator) The Data Wrapper ---------------- The ``Data`` class provides a wrapper to present a dictionary as a class instance. This is used to check for invariants, which always expect an object. While the common use cases of the data wrapper are well tested in the code above, there are some corner cases that need to be addressed. So let's start by creating a data object: >>> context = object() >>> data = validator.Data(IPerson, {'login': 'srichter', 'other': 1}, context) When we try to access a name that is not in the schema, we get an attribute error: >>> data.address Traceback (most recent call last): ... AttributeError: address >>> data.other Traceback (most recent call last): ... AttributeError: other If the field found is a method, then a runtime error is raised: >>> class IExtendedPerson(IPerson): ... def compute(): ... """Compute something.""" >>> data = validator.Data(IExtendedPerson, {'compute': 1}, context) >>> data.compute Traceback (most recent call last): ... RuntimeError: ('Data value is not a schema field', 'compute') Finally, the context is available as attribute directly: >>> data.__context__ is context True It is used by the validators (especially invariant validators) to provide a context of validation, for example to look up a vocabulary or access the parent of an object. Note that the context will be different between add and edit forms. Validation of interface variants when not all fields are displayed in form -------------------------------------------------------------------------- We need to register the data manager to access the data on the context object: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.AttributeField) Sometimes you might leave out fields in the form which need to compute the invariant. An exception should be raised. The data wrapper is used to test the invariants and looks up values on the context object that are left out in the form. >>> invariants = validator.InvariantsValidator( ... stephan, None, None, IPerson, None) >>> errors = invariants.validate({'email': '[email protected]'}) >>> errors[0].__class__.__name__ 'Invalid' >>> errors[0].args[0] 'The login not part of email.'
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/validator.rst
validator.rst
__docformat__ = "reStructuredText" import os import zope.component import zope.interface import zope.schema from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.pagetemplate.interfaces import IPageTemplate import z3c.form from z3c.form import interfaces from z3c.form import util from z3c.form import value from z3c.form.i18n import MessageFactory as _ ErrorViewMessage = value.StaticValueCreator( discriminators=('error', 'request', 'widget', 'field', 'form', 'content') ) ComputedErrorViewMessage = value.ComputedValueCreator( discriminators=('error', 'request', 'widget', 'field', 'form', 'content') ) def ErrorViewDiscriminators( errorView, error=None, request=None, widget=None, field=None, form=None, content=None): zope.component.adapter( util.getSpecification(error), util.getSpecification(request), util.getSpecification(widget), util.getSpecification(field), util.getSpecification(form), util.getSpecification(content))(errorView) @zope.interface.implementer(interfaces.IErrorViewSnippet) class ErrorViewSnippet: """Error view snippet.""" zope.component.adapts( zope.schema.ValidationError, None, None, None, None, None) def __init__(self, error, request, widget, field, form, content): self.error = self.context = error self.request = request self.widget = widget self.field = field self.form = form self.content = content def createMessage(self): return self.error.doc() def update(self): value = zope.component.queryMultiAdapter( (self.context, self.request, self.widget, self.field, self.form, self.content), interfaces.IValue, name='message') if value is not None: self.message = value.get() else: self.message = self.createMessage() def render(self): template = zope.component.getMultiAdapter( (self, self.request), IPageTemplate) return template(self) def __repr__(self): return '<{} for {}>'.format( self.__class__.__name__, self.error.__class__.__name__) class ValueErrorViewSnippet(ErrorViewSnippet): """An error view for ValueError.""" zope.component.adapts( ValueError, None, None, None, None, None) defaultMessage = _('The system could not process the given value.') def createMessage(self): return self.defaultMessage class InvalidErrorViewSnippet(ErrorViewSnippet): """Error view snippet.""" zope.component.adapts( zope.interface.Invalid, None, None, None, None, None) def createMessage(self): return self.error.args[0] class MultipleErrorViewSnippet(ErrorViewSnippet): """Error view snippet for multiple errors.""" zope.component.adapts( interfaces.IMultipleErrors, None, None, None, None, None) def update(self): pass def render(self): return ''.join([view.render() for view in self.error.errors]) @zope.interface.implementer(interfaces.IMultipleErrors) class MultipleErrors(Exception): """An error that contains many errors""" def __init__(self, errors): self.errors = errors class ErrorViewTemplateFactory: """Error view template factory.""" template = None def __init__(self, filename, contentType='text/html'): self.template = ViewPageTemplateFile( filename, content_type=contentType) def __call__(self, errorView, request): return self.template # Create the standard error view template StandardErrorViewTemplate = ErrorViewTemplateFactory( os.path.join(os.path.dirname(z3c.form.__file__), 'error.pt'), 'text/html') zope.component.adapter( interfaces.IErrorViewSnippet, None)(StandardErrorViewTemplate) zope.interface.implementer(IPageTemplate)(StandardErrorViewTemplate)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/error.py
error.py
============================= Utility Functions and Classes ============================= This file documents the utility functions and classes that are otherwise not tested. >>> from z3c.form import util ``createId(name)`` Function --------------------------- This function converts an arbitrary unicode string into a valid Python identifier. If the name is a valid identifier, then it is just returned, but all upper case letters are lowered: >>> util.createId('Change') 'change' >>> util.createId('Change_2') 'change_2' If a name is not a valid identifier, a hex code of the string is created: >>> util.createId('Change 3') '4368616e67652033' The function can also handle non-ASCII characters: >>> id = util.createId('Ändern') Since the output depends on how Python is compiled (UCS-2 or 4), we only check that we have a valid id: >>> util._identifier.match(id) is not None True ``createCSSId(name)`` Function ------------------------------ This function takes any unicode name and coverts it into an id that can be easily referenced by CSS selectors. Characters that are in the ascii alphabet, are numbers, or are '-' or '_' will be left the same. All other characters will be converted to ordinal numbers: >>> util.createCSSId('NormalId') 'NormalId' >>> id = util.createCSSId('عَرَ') >>> util._identifier.match(id) is not None True >>> util.createCSSId('This has spaces') 'This20has20spaces' >>> util.createCSSId(str([(1, 'x'), ('foobar', 42)])) '5b2812c2027x27292c202827foobar272c2042295d' ``getWidgetById(form, id)`` Function ------------------------------------ Given a form and a widget id, this function extracts the widget for you. First we need to create a properly developed form: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... name = zope.schema.TextLine(title='Name') >>> from z3c.form import form, field >>> class AddPerson(form.AddForm): ... fields = field.Fields(IPerson) >>> from z3c.form import testing >>> testing.setupFormDefaults() >>> addPerson = AddPerson(None, testing.TestRequest()) >>> addPerson.update() We can now ask for the widget: >>> util.getWidgetById(addPerson, 'form-widgets-name') <TextWidget 'form.widgets.name'> The widget id can be split into a prefix and a widget name. The id must always start with the correct prefix, otherwise a value error is raised: >>> util.getWidgetById(addPerson, 'myform-widgets-name') Traceback (most recent call last): ... ValueError: Name 'myform.widgets.name' must start with prefix 'form.widgets.' If the widget is not found but the prefix is correct, ``None`` is returned: >>> util.getWidgetById(addPerson, 'form-widgets-myname') is None True ``extractFileName(form, id, cleanup=True, allowEmptyPostfix=False)`` Function ----------------------------------------------------------------------------- Test the filename extraction method: >>> class IDocument(zope.interface.Interface): ... data = zope.schema.Bytes(title='Data') Define a widgets stub and a upload widget stub class and setup them as a faked form: >>> class FileUploadWidgetStub(object): ... def __init__(self): ... self.filename = None >>> class WidgetsStub(object): ... def __init__(self): ... self.data = FileUploadWidgetStub() ... self.prefix = 'widgets.' ... def get(self, name, default): ... return self.data >>> class FileUploadFormStub(form.AddForm): ... def __init__(self): ... self.widgets = WidgetsStub() ... ... def setFakeFileName(self, filename): ... self.widgets.data.filename = filename Now we can setup the stub form. Note this form is just a fake it's not a real implementation. We just provide a form like class which simulates the FileUpload object in the a widget. See `z3c/form/browser/file.rst` for a real file upload test uscase: >>> uploadForm = FileUploadFormStub() >>> uploadForm.setFakeFileName('foo.txt') And extract the filename >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.txt' Test a unicode filename: >>> uploadForm.setFakeFileName('foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.txt' Test a windows IE uploaded filename: >>> uploadForm.setFakeFileName('D:\\some\\folder\\foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.txt' Test another filename: >>> uploadForm.setFakeFileName('D:/some/folder/foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.txt' Test another filename: >>> uploadForm.setFakeFileName('/tmp/folder/foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.txt' Test special characters in filename, e.g. dots: >>> uploadForm.setFakeFileName('/tmp/foo.bar.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo.bar.txt' Test some other special characters in filename: >>> uploadForm.setFakeFileName('/tmp/foo-bar.v.0.1.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo-bar.v.0.1.txt' Test special characters in file path of filename: >>> uploadForm.setFakeFileName('/tmp-v.1.0/foo-bar.v.0.1.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) 'foo-bar.v.0.1.txt' Test optional keyword arguments. But remember it's hard for Zope to guess the content type for filenames without extensions: >>> uploadForm.setFakeFileName('minimal') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True, ... allowEmptyPostfix=True) 'minimal' >>> uploadForm.setFakeFileName('/tmp/minimal') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True, ... allowEmptyPostfix=True) 'minimal' >>> uploadForm.setFakeFileName('D:\\some\\folder\\minimal') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True, ... allowEmptyPostfix=True) 'minimal' There will be a ValueError if we get a empty filename by default: >>> uploadForm.setFakeFileName('/tmp/minimal') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=True) Traceback (most recent call last): ... ValueError: Missing filename extension. We also can skip removing a path from a upload. Note only IE will upload a path in a upload ``<input type="file" ...>`` field: >>> uploadForm.setFakeFileName('/tmp/foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=False) '/tmp/foo.txt' >>> uploadForm.setFakeFileName('/tmp-v.1.0/foo-bar.v.0.1.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=False) '/tmp-v.1.0/foo-bar.v.0.1.txt' >>> uploadForm.setFakeFileName('D:\\some\\folder\\foo.txt') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=False) 'D:\\some\\folder\\foo.txt' And missing filename extensions are also not allowed by deafault if we skip the filename: >>> uploadForm.setFakeFileName('/tmp/minimal') >>> util.extractFileName(uploadForm, 'form.widgets.data', cleanup=False) Traceback (most recent call last): ... ValueError: Missing filename extension. ``extractContentType(form, id)`` Function ----------------------------------------- There is also a method which is able to extract the content type for a given file upload. We can use the stub form from the previous test. Not sure if this an error but on my windows system this test returns image/pjpeg (progressive jpeg) for foo.jpg and image/x-png for foo.png. So let's allow this too since this depends on guess_content_type and is not really a part of z3c.form. >>> uploadForm = FileUploadFormStub() >>> uploadForm.setFakeFileName('foo.txt') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'text/plain' >>> uploadForm.setFakeFileName('foo.gif') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'image/gif' >>> uploadForm.setFakeFileName('foo.jpg') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'image/...jpeg' >>> uploadForm.setFakeFileName('foo.png') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'image/...png' >>> uploadForm.setFakeFileName('foo.tif') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'image/tiff' >>> uploadForm.setFakeFileName('foo.doc') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'application/msword' >>> uploadForm.setFakeFileName('foo.zip') >>> (util.extractContentType(uploadForm, 'form.widgets.data') ... in ('application/zip', 'application/x-zip-compressed')) True >>> uploadForm.setFakeFileName('foo.unknown') >>> util.extractContentType(uploadForm, 'form.widgets.data') 'text/x-unknown-content-type' `Manager` object ---------------- The manager object is a base class of a mapping object that keeps track of the key order as they are added. >>> manager = util.Manager() Initially the manager is empty: >>> len(manager) 0 Since this base class mainly defines a read-interface, we have to add the values manually: >>> manager['b'] = 2 >>> manager['a'] = 1 Let's iterate through the manager: >>> tuple(iter(manager)) ('b', 'a') >>> list(manager.keys()) ['b', 'a'] >>> list(manager.values()) [2, 1] >>> list(manager.items()) [('b', 2), ('a', 1)] Let's ow look at item access: >>> 'b' in manager True >>> manager.get('b') 2 >>> manager.get('c', 'None') 'None' It also supports deletion: >>> del manager['b'] >>> list(manager.items()) [('a', 1)] `SelectionManager` object ------------------------- The selection manager is an extension to the manager and provides a few more API functions. Unfortunately, this base class is totally useless without a sensible constructor: >>> import zope.interface >>> class MySelectionManager(util.SelectionManager): ... managerInterface = zope.interface.Interface ... ... def __init__(self, *args): ... super(MySelectionManager, self).__init__() ... args = list(args) ... for arg in args: ... if isinstance(arg, MySelectionManager): ... args += arg.values() ... continue ... self[str(arg)] = arg Let's now create two managers: >>> manager1 = MySelectionManager(1, 2) >>> manager2 = MySelectionManager(3, 4) You can add two managers: >>> manager = manager1 + manager2 >>> list(manager.values()) [1, 2, 3, 4] Next, you can select only certain names: >>> list(manager.select('1', '2', '3').values()) [1, 2, 3] Or simply omit a value. >>> list(manager.omit('2').values()) [1, 3, 4] You can also easily copy a manager: >>> manager.copy() is not manager True That's all. `getSpecification()` function ----------------------------- This function is capable of returning an `ISpecification` for any object, including instances. For an interface, it simply returns the interface: >>> import zope.interface >>> class IFoo(zope.interface.Interface): ... pass >>> util.getSpecification(IFoo) == IFoo True Ditto for a class: >>> class Bar(object): ... pass >>> util.getSpecification(Bar) == Bar True For an instance, it will create a marker interface on the fly if necessary: >>> bar = Bar() >>> util.getSpecification(bar) # doctest: +ELLIPSIS <InterfaceClass z3c.form.util.IGeneratedForObject_...> The ellipsis represents a hash of the object. If the function is called twice on the same object, it will not create a new marker each time: >>> baz = Bar() >>> barMarker = util.getSpecification(bar) >>> bazMarker1 = util.getSpecification(baz) >>> bazMarker2 = util.getSpecification(baz) >>> barMarker is bazMarker1 False >>> bazMarker1 == bazMarker2 True >>> bazMarker1 is bazMarker2 True `changedField()` function ------------------------- Decide whether a field was changed/modified. >>> class IPerson(zope.interface.Interface): ... login = zope.schema.TextLine( ... title='Login') ... address = zope.schema.Object( ... schema=zope.interface.Interface) >>> @zope.interface.implementer(IPerson) ... class Person(object): ... login = 'johndoe' >>> person = Person() field.context is None and no context passed: >>> util.changedField(IPerson['login'], 'foo') True IObject field: >>> util.changedField(IPerson['address'], object(), context = person) True field.context or context passed: >>> import z3c.form.datamanager >>> zope.component.provideAdapter(z3c.form.datamanager.AttributeField) >>> util.changedField(IPerson['login'], 'foo', context = person) True >>> util.changedField(IPerson['login'], 'johndoe', context = person) False >>> fld = IPerson['login'].bind(person) >>> util.changedField(fld, 'foo') True >>> util.changedField(fld, 'johndoe') False No access: >>> save = z3c.form.datamanager.AttributeField.canAccess >>> z3c.form.datamanager.AttributeField.canAccess = lambda self: False >>> util.changedField(IPerson['login'], 'foo', context = person) True >>> util.changedField(IPerson['login'], 'johndoe', context = person) True >>> z3c.form.datamanager.AttributeField.canAccess = save `changedWidget()` function --------------------------- Decide whether a widget value was changed/modified. >>> import z3c.form.testing >>> request = z3c.form.testing.TestRequest() >>> import z3c.form.widget >>> widget = z3c.form.widget.Widget(request) If the widget is not IContextAware, there's nothing to check: >>> from z3c.form import interfaces >>> interfaces.IContextAware.providedBy(widget) False >>> util.changedWidget(widget, 'foo') True Make it IContextAware: >>> widget.context = person >>> zope.interface.alsoProvides(widget, interfaces.IContextAware) >>> widget.field = IPerson['login'] >> util.changedWidget(widget, 'foo') True >>> util.changedWidget(widget, 'johndoe') False Field and context is also overridable: >>> widget.field = None >>> util.changedWidget(widget, 'johndoe', field=IPerson['login']) False >>> p2 = Person() >>> p2.login = 'foo' >>> util.changedWidget(widget, 'foo', field=IPerson['login'], context=p2) False `sortedNone()` function ------------------------ >>> util.sortedNone([None, 'a', 'b']) [None, 'a', 'b'] >>> util.sortedNone([None, 1, 2]) [None, 1, 2] >>> util.sortedNone([None, True, False]) [None, False, True] >>> util.sortedNone([['true'], [], ['false']]) [[], ['false'], ['true']] >>> util.sortedNone([('false',), ('true',), ()]) [(), ('false',), ('true',)]
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/util.rst
util.rst
__docformat__ = "reStructuredText" import copy import zope.component import zope.interface import zope.schema from z3c.form import interfaces from z3c.form import util @zope.interface.implementer(interfaces.IValidator) class StrictSimpleFieldValidator: """Strict Simple Field Validator validates all incoming values""" zope.component.adapts( zope.interface.Interface, zope.interface.Interface, zope.interface.Interface, zope.schema.interfaces.IField, zope.interface.Interface) def __init__(self, context, request, view, field, widget): self.context = context self.request = request self.view = view self.field = field self.widget = widget def validate(self, value, force=False): """See interfaces.IValidator""" context = self.context field = self.field widget = self.widget if field.required and widget and widget.ignoreRequiredOnValidation: # make the field not-required while checking field = copy.copy(field) field.required = False if context is not None: field = field.bind(context) if value is interfaces.NOT_CHANGED: if (interfaces.IContextAware.providedBy(widget) and not widget.ignoreContext): # get value from context value = zope.component.getMultiAdapter( (context, field), interfaces.IDataManager).query() else: value = interfaces.NO_VALUE if value is interfaces.NO_VALUE: # look up default value value = field.default adapter = zope.component.queryMultiAdapter( (context, self.request, self.view, field, widget), interfaces.IValue, name='default') if adapter: value = adapter.get() return field.validate(value) def __repr__(self): return "<{} for {}['{}']>".format( self.__class__.__name__, self.field.interface.getName(), self.field.__name__) class SimpleFieldValidator(StrictSimpleFieldValidator): """Simple Field Validator ignores unchanged values""" def validate(self, value, force=False): """See interfaces.IValidator""" if value is self.field.missing_value: # let missing values run into stricter validation # most important case is not let required fields pass return super().validate(value, force) if not force: if value is interfaces.NOT_CHANGED: # no need to validate unchanged values return if self.widget and not util.changedWidget( self.widget, value, field=self.field, context=self.context): # if new value == old value, no need to validate return # otherwise StrictSimpleFieldValidator will do the job return super().validate(value, force) class FileUploadValidator(StrictSimpleFieldValidator): """File upload validator """ zope.component.adapts( zope.interface.Interface, zope.interface.Interface, zope.interface.Interface, zope.schema.interfaces.IBytes, interfaces.IFileWidget) # only FileUploadDataConverter seems to use NOT_CHANGED, but that needs # to be validated, because file upload is a special case # the most special case if when an ad-hoc IBytes field is required def WidgetValidatorDiscriminators( validator, context=None, request=None, view=None, field=None, widget=None): zope.component.adapter( util.getSpecification(context), util.getSpecification(request), util.getSpecification(view), util.getSpecification(field), util.getSpecification(widget))(validator) class NoInputData(zope.interface.Invalid): """There was no input data because: - It wasn't asked for - It wasn't entered by the user - It was entered by the user, but the value entered was invalid This exception is part of the internal implementation of checkInvariants. """ @zope.interface.implementer(interfaces.IData) class Data: def __init__(self, schema, data, context): self._Data_data___ = data self._Data_schema___ = schema zope.interface.alsoProvides(self, schema) self.__context__ = context def __getattr__(self, name): schema = self._Data_schema___ data = self._Data_data___ try: field = schema[name] except KeyError: raise AttributeError(name) # If the found field is a method, then raise an error. if zope.interface.interfaces.IMethod.providedBy(field): raise RuntimeError("Data value is not a schema field", name) # Try to get the value for the field value = data.get(name, data) if value is data: if self.__context__ is None: raise NoInputData(name) dm = zope.component.getMultiAdapter( (self.__context__, field), interfaces.IDataManager) value = dm.get() # Optimization: Once we know we have a good value, set it as an # attribute for faster access. setattr(self, name, value) return value @zope.interface.implementer(interfaces.IManagerValidator) class InvariantsValidator: """Simple Field Validator""" zope.component.adapts( zope.interface.Interface, zope.interface.Interface, zope.interface.Interface, zope.interface.interfaces.IInterface, zope.interface.Interface) def __init__(self, context, request, view, schema, manager): self.context = context self.request = request self.view = view self.schema = schema self.manager = manager def validate(self, data): """See interfaces.IManagerValidator""" return self.validateObject(Data(self.schema, data, self.context)) def validateObject(self, object): errors = [] try: self.schema.validateInvariants(object, errors) except zope.interface.Invalid: pass # Just collect the errors return tuple([error for error in errors if not isinstance(error, NoInputData)]) def __repr__(self): return f'<{self.__class__.__name__} for {self.schema.getName()}>' def WidgetsValidatorDiscriminators( validator, context=None, request=None, view=None, schema=None, manager=None): zope.component.adapter( util.getSpecification(context), util.getSpecification(request), util.getSpecification(view), util.getSpecification(schema), util.getSpecification(manager))(validator)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/validator.py
validator.py
===== Terms ===== Terms are used to provide choices for sequence widgets or any other construct needing them. Since Zope 3 already has sources and vocabularies, the base terms class simply builds on them. Vocabularies ------------ Thus, let's create a vocabulary first: >>> from zope.schema import vocabulary >>> ratings = vocabulary.SimpleVocabulary([ ... vocabulary.SimpleVocabulary.createTerm(0, '0', 'bad'), ... vocabulary.SimpleVocabulary.createTerm(1, '1', 'okay'), ... vocabulary.SimpleVocabulary.createTerm(2, '2', 'good') ... ]) Terms ~~~~~ Now we can create the terms object: >>> from z3c.form import term >>> terms = term.Terms() >>> terms.terms = ratings Getting a term from a given value is simple: >>> terms.getTerm(0).title 'bad' >>> terms.getTerm(3) Traceback (most recent call last): ... LookupError: 3 When converting values from their Web representation back to the internal representation, we have to be able to look up a term by its token: >>> terms.getTermByToken('0').title 'bad' >>> terms.getTerm('3') Traceback (most recent call last): ... LookupError: 3 However, often we just want the value so asking for the value that is represented by a token saves usually one line of code: >>> terms.getValue('0') 0 >>> terms.getValue('3') Traceback (most recent call last): ... LookupError: 3 You can also iterate through all terms: >>> [entry.title for entry in terms] ['bad', 'okay', 'good'] Or ask how many terms you have in the first place: >>> len(terms) 3 Finally the API allows you to check whether a particular value is available in the terms: >>> 0 in terms True >>> 3 in terms False Now, there are several terms implementations that were designed for particular fields. Within the framework, terms are used as adapters with the follwoing discriminators: context, request, form, field, vocabulary/source and widget. Choice field ~~~~~~~~~~~~ The first terms implementation is for ``Choice`` fields. Choice fields unfortunately can have a vocabulary and a source which behave differently. Let's have a look a the vocabulary first: >>> import zope.component >>> zope.component.provideAdapter(term.ChoiceTermsVocabulary) >>> import z3c.form.testing >>> request = z3c.form.testing.TestRequest() >>> import z3c.form.widget >>> widget = z3c.form.widget.Widget(request) >>> import zope.schema >>> ratingField = zope.schema.Choice( ... title='Rating', ... vocabulary=ratings) >>> terms = term.ChoiceTerms( ... None, request, None, ratingField, widget) >>> [entry.title for entry in terms] ['bad', 'okay', 'good'] Sometimes choice fields only specify a vocabulary name and the actual vocabulary is looked up at run time. >>> ratingField2 = zope.schema.Choice( ... title='Rating', ... vocabulary='Ratings') Initially we get an error because the "Ratings" vocabulary is not defined: >>> terms = term.ChoiceTerms( ... None, request, None, ratingField2, widget) Traceback (most recent call last): ... MissingVocabularyError: Can't validate value without vocabulary named 'Ratings' Let's now register the vocabulary under this name: >>> def RatingsVocabulary(obj): ... return ratings >>> from zope.schema import vocabulary >>> vr = vocabulary.getVocabularyRegistry() >>> vr.register('Ratings', RatingsVocabulary) We should now be able to get all terms as before: >>> terms = term.ChoiceTerms( ... None, request, None, ratingField, widget) >>> [entry.title for entry in terms] ['bad', 'okay', 'good'] Missing terms +++++++++++++ Sometimes it happens that a term goes away from the vocabulary, but our stored objects still reference that term. >>> zope.component.provideAdapter(term.MissingChoiceTermsVocabulary) >>> terms = term.ChoiceTerms( ... None, request, None, ratingField, widget) >>> term = terms.getTermByToken('42') Traceback (most recent call last): ... LookupError: 42 The same goes with looking up a term by value: >>> term = terms.getTerm('42') Traceback (most recent call last): ... LookupError: 42 Ooops, well this works only if the context has the right value for us. This is because we don't want to accept any crap that's coming from HTML. >>> class IPerson(zope.interface.Interface): ... gender = zope.schema.Choice(title='Gender', vocabulary='Genders') >>> @zope.interface.implementer(IPerson) ... class Person(object): ... gender = None >>> gendersVocabulary = vocabulary.SimpleVocabulary([ ... vocabulary.SimpleVocabulary.createTerm(1, 'male', 'Male'), ... vocabulary.SimpleVocabulary.createTerm(2, 'female', 'Female'), ... ]) >>> def GendersVocabulary(obj): ... return ratings >>> vr.register('Genders', GendersVocabulary) >>> ctx = Person() >>> ctx.gender = 42 >>> genderWidget = z3c.form.widget.Widget(request) >>> genderWidget.context = ctx >>> from z3c.form import interfaces >>> zope.interface.alsoProvides(genderWidget, interfaces.IContextAware) >>> from z3c.form.datamanager import AttributeField >>> zope.component.provideAdapter(AttributeField) >>> terms = term.ChoiceTerms( ... ctx, request, None, IPerson['gender'], genderWidget) Here we go: >>> missingTerm = terms.getTermByToken('42') We get the term, we passed the token, the value is coming from the context. >>> missingTerm.token '42' >>> missingTerm.value 42 We cannot figure the title, so we construct one. Override ``makeMissingTerm`` if you want your own. >>> missingTerm.title 'Missing: ${value}' Still we raise LookupError if the token does not fit the context's value: >>> missingTerm = terms.getTermByToken('99') Traceback (most recent call last): ... LookupError: 99 The same goes with looking up a term by value. We get the term if the context's value fits: >>> missingTerm = terms.getTerm(42) >>> missingTerm.token '42' And an exception if it does not: >>> missingTerm = terms.getTerm(99) Traceback (most recent call last): ... LookupError: 99 Bool fields ~~~~~~~~~~~ A similar terms implementation exists for a ``Bool`` field: >>> truthField = zope.schema.Bool() >>> terms = term.BoolTerms(None, None, None, truthField, None) >>> [entry.title for entry in terms] ['yes', 'no'] In case you don't like the choice of 'yes' and 'no' for the labels, we can subclass the ``BoolTerms`` class to control the display labels. >>> class MyBoolTerms(term.BoolTerms): ... trueLabel = 'True' ... falseLabel = 'False' >>> terms = MyBoolTerms(None, None, None, truthField, None) >>> [entry.title for entry in terms] ['True', 'False'] Collections ~~~~~~~~~~~ Finally, there are a terms adapters for all collections. But we have to register some adapters before using it: >>> from z3c.form import term >>> zope.component.provideAdapter(term.CollectionTerms) >>> zope.component.provideAdapter(term.CollectionTermsVocabulary) >>> zope.component.provideAdapter(term.CollectionTermsSource) >>> ratingsField = zope.schema.List( ... title='Ratings', ... value_type=ratingField) >>> terms = term.CollectionTerms( ... None, request, None, ratingsField, widget) >>> [entry.title for entry in terms] ['bad', 'okay', 'good'] Sources ------- Basic sources ~~~~~~~~~~~~~ Basic sources need no context to compute their value. Let's create a source first: >>> from zc.sourcefactory.basic import BasicSourceFactory >>> class RatingSourceFactory(BasicSourceFactory): ... _mapping = {10: 'ugly', 20: 'nice', 30: 'great'} ... def getValues(self): ... return self._mapping.keys() ... def getTitle(self, value): ... return self._mapping[value] As we did not include the configure.zcml of zc.sourcefactory we have to register some required adapters manually. We also need the ChoiceTermsSource adapter: >>> import zope.component >>> import zc.sourcefactory.browser.source >>> import zc.sourcefactory.browser.token >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.source.FactoredTerms) >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.token.fromInteger) >>> zope.component.provideAdapter(term.ChoiceTermsSource) Choice fields +++++++++++++ Sources can be used with ``Choice`` fields like vocabularies. First we create a field based on the source: >>> sourceRatingField = zope.schema.Choice( ... title='Sourced Rating', ... source=RatingSourceFactory()) We connect the field to a widget to see the ITerms adapter for sources at work: >>> terms = term.ChoiceTerms( ... None, request, None, sourceRatingField, widget) Iterating over the terms adapter returnes the term objects: >>> [entry for entry in terms] [<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>, <zc.sourcefactory.browser.source.FactoredTerm object at 0x...>, <zc.sourcefactory.browser.source.FactoredTerm object at 0x...>] >>> len(terms) 3 >>> [entry.token for entry in terms] ['10', '20', '30'] >>> [entry.title for entry in terms] ['ugly', 'nice', 'great'] Using a token it is possible to look up the term and the value: >>> terms.getTermByToken('20').title 'nice' >>> terms.getValue('30') 30 With can test if a value is in the source: >>> 30 in terms True >>> 25 in terms False Missing terms ############# Sometimes it happens that a value goes away from the source, but our stored objects still has this value. >>> zope.component.provideAdapter(term.MissingChoiceTermsSource) >>> terms = term.ChoiceTerms( ... None, request, None, sourceRatingField, widget) >>> terms.getTermByToken('42') Traceback (most recent call last): ... LookupError: 42 The same goes with looking up a term by value: >>> terms.getTerm(42) Traceback (most recent call last): ... LookupError: 42 Ooops, well this works only if the context has the right value for us. This is because we don't want to accept any crap that's coming from HTML. >>> class IRating(zope.interface.Interface): ... rating = zope.schema.Choice(title='Sourced Rating', ... source=RatingSourceFactory()) >>> @zope.interface.implementer(IRating) ... class Rating(object): ... rating = None >>> ctx = Rating() >>> ctx.rating = 42 >>> ratingWidget = z3c.form.widget.Widget(request) >>> ratingWidget.context = ctx >>> from z3c.form import interfaces >>> zope.interface.alsoProvides(ratingWidget, interfaces.IContextAware) >>> from z3c.form.datamanager import AttributeField >>> zope.component.provideAdapter(AttributeField) >>> terms = term.ChoiceTerms( ... ctx, request, None, IRating['rating'], ratingWidget) Here we go: >>> missingTerm = terms.getTermByToken('42') We get the term, we passed the token, the value is coming from the context. >>> missingTerm.token '42' >>> missingTerm.value 42 We cannot figure the title, so we construct one. Override ``makeMissingTerm`` if you want your own. >>> missingTerm.title 'Missing: ${value}' Still we raise LookupError if the token does not fit the context's value: >>> missingTerm = terms.getTermByToken('99') Traceback (most recent call last): ... LookupError: 99 The same goes with looking up a term by value. We get the term if the context's value fits: >>> missingTerm = terms.getTerm(42) >>> missingTerm.token '42' And an exception if it does not: >>> missingTerm = terms.getTerm(99) Traceback (most recent call last): ... LookupError: 99 Collections +++++++++++ Finally, there are terms adapters for all collections: >>> sourceRatingsField = zope.schema.List( ... title='Sourced Ratings', ... value_type=sourceRatingField) >>> terms = term.CollectionTerms( ... None, request, None, sourceRatingsField, widget) >>> [entry.title for entry in terms] ['ugly', 'nice', 'great'] Contextual sources ~~~~~~~~~~~~~~~~~~ Contextual sources depend on the context they are called on. Let's create a context and a contextual source: >>> from zc.sourcefactory.contextual import BasicContextualSourceFactory >>> class RatingContext(object): ... base_value = 10 >>> class ContextualRatingSourceFactory(BasicContextualSourceFactory): ... _mapping = {10: 'ugly', 20: 'nice', 30: 'great'} ... def getValues(self, context): ... return [context.base_value + x for x in self._mapping.keys()] ... def getTitle(self, context, value): ... return self._mapping[value - context.base_value] As we did not include the configure.zcml of zc.sourcefactory we have to register some required adapters manually. We also need the ChoiceTermsSource adapter: >>> import zope.component >>> import zc.sourcefactory.browser.source >>> import zc.sourcefactory.browser.token >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.source.FactoredContextualTerms) >>> zope.component.provideAdapter( ... zc.sourcefactory.browser.token.fromInteger) >>> zope.component.provideAdapter(term.ChoiceTermsSource) Choice fields +++++++++++++ Contextual sources can be used with ``Choice`` fields like vocabularies. First we create a field based on the source: >>> contextualSourceRatingField = zope.schema.Choice( ... title='Context Sourced Rating', ... source=ContextualRatingSourceFactory()) We create an context object and connect the field to a widget to see the ITerms adapter for sources at work: >>> rating_context = RatingContext() >>> rating_context.base_value = 100 >>> terms = term.ChoiceTerms( ... rating_context, request, None, contextualSourceRatingField, widget) Iterating over the terms adapter returnes the term objects: >>> [entry for entry in terms] [<zc.sourcefactory.browser.source.FactoredTerm object at 0x...>, <zc.sourcefactory.browser.source.FactoredTerm object at 0x...>, <zc.sourcefactory.browser.source.FactoredTerm object at 0x...>] >>> len(terms) 3 >>> [entry.token for entry in terms] ['110', '120', '130'] >>> [entry.title for entry in terms] ['ugly', 'nice', 'great'] Using a token, it is possible to look up the term and the value: >>> terms.getTermByToken('120').title 'nice' >>> terms.getValue('130') 130 With can test if a value is in the source: >>> 130 in terms True >>> 125 in terms False Collections +++++++++++ Finally, there are terms adapters for all collections: >>> contextualSourceRatingsField = zope.schema.List( ... title='Contextual Sourced Ratings', ... value_type=contextualSourceRatingField) >>> terms = term.CollectionTerms( ... rating_context, request, None, contextualSourceRatingsField, widget) >>> [entry.title for entry in terms] ['ugly', 'nice', 'great'] Missing terms in collections ############################ Sometimes it happens that a value goes away from the source, but our stored collection still has this value. >>> zope.component.provideAdapter(term.MissingCollectionTermsSource) >>> terms = term.CollectionTerms( ... RatingContext(), request, None, contextualSourceRatingsField, widget) >>> terms <z3c.form.term.MissingCollectionTermsSource object at 0x...> >>> terms.getTermByToken('42') Traceback (most recent call last): ... LookupError: 42 The same goes with looking up a term by value: >>> terms.getTerm(42) Traceback (most recent call last): ... LookupError: 42 The same goes with looking up a value by the token: >>> terms.getValue('42') Traceback (most recent call last): ... LookupError: 42 Ooops, well this works only if the context has the right value for us. This is because we don't want to accept any crap that's coming from HTML. >>> class IRatings(zope.interface.Interface): ... ratings = zope.schema.List( ... title='Contextual Sourced Ratings', ... value_type=contextualSourceRatingField) >>> @zope.interface.implementer(IRatings) ... class Ratings(object): ... ratings = None ... base_value = 10 >>> ctx = Ratings() >>> ctx.ratings = [42, 10] >>> ratingsWidget = z3c.form.widget.Widget(request) >>> ratingsWidget.context = ctx >>> from z3c.form import interfaces >>> zope.interface.alsoProvides(ratingsWidget, interfaces.IContextAware) >>> from z3c.form.datamanager import AttributeField >>> zope.component.provideAdapter(AttributeField) >>> terms = term.CollectionTerms( ... ctx, request, None, IRatings['ratings'], ratingsWidget) Here we go: >>> term = terms.getTerm(42) >>> missingTerm = terms.getTermByToken('42') We get the term, we passed the token, the value is coming from the context. >>> missingTerm.token '42' >>> missingTerm.value 42 We cannot figure the title, so we construct one. Override ``makeMissingTerm`` if you want your own. >>> missingTerm.title 'Missing: ${value}' We can get the value for a missing term: >>> terms.getValue('42') 42 Still we raise LookupError if the token does not fit the context's value: >>> missingTerm = terms.getTermByToken('99') Traceback (most recent call last): ... LookupError: 99 The same goes with looking up a term by value. We get the term if the context's value fits: >>> missingTerm = terms.getTerm(42) >>> missingTerm.token '42' And an exception if it does not: >>> missingTerm = terms.getTerm(99) Traceback (most recent call last): ... LookupError: 99
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/term.rst
term.rst
__docformat__ = "reStructuredText" import zope.component import zope.event import zope.interface import zope.lifecycleevent import zope.schema from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.pagetemplate.interfaces import IPageTemplate from zope.security.proxy import removeSecurityProxy from z3c.form import field from z3c.form import interfaces from z3c.form import util from z3c.form import widget from z3c.form.converter import BaseDataConverter from z3c.form.error import MultipleErrors def getIfName(iface): return iface.__module__ + '.' + iface.__name__ # our own placeholder instead of a simple None class ObjectWidget_NO_VALUE: def __repr__(self): return '<ObjectWidget_NO_VALUE>' ObjectWidget_NO_VALUE = ObjectWidget_NO_VALUE() class ObjectWidgetValue(dict): originalValue = ObjectWidget_NO_VALUE # will store the original object class ObjectConverter(BaseDataConverter): """Data converter for IObjectWidget.""" zope.component.adapts( zope.schema.interfaces.IObject, interfaces.IObjectWidget) def toWidgetValue(self, value): """Just dispatch it.""" if value is self.field.missing_value: return interfaces.NO_VALUE retval = ObjectWidgetValue() retval.originalValue = value for name, field_ in zope.schema.getFieldsInOrder(self.field.schema): dm = zope.component.getMultiAdapter( (value, field_), interfaces.IDataManager) subv = dm.query() if subv is interfaces.NO_VALUE: # look up default value subv = field_.default # XXX: too many discriminators # adapter = zope.component.queryMultiAdapter( # (context, self.request, self.view, field, widget), # interfaces.IValue, name='default') # if adapter: # value = adapter.get() widget = zope.component.getMultiAdapter( (field_, self.widget.request), interfaces.IFieldWidget) if interfaces.IFormAware.providedBy(self.widget): # form property required by objectwidget widget.form = self.widget.form zope.interface.alsoProvides(widget, interfaces.IFormAware) converter = zope.component.getMultiAdapter( (field_, widget), interfaces.IDataConverter) retval[name] = converter.toWidgetValue(subv) return retval def adapted_obj(self, obj): return self.field.schema(obj) def toFieldValue(self, value): """field value is an Object type, that provides field.schema""" if value is interfaces.NO_VALUE: return self.field.missing_value # try to get the original object, or if there's no chance an empty one obj = self.widget.getObject(value) obj = self.adapted_obj(obj) names = [] for name, field_ in zope.schema.getFieldsInOrder(self.field.schema): if not field_.readonly: try: newvalRaw = value[name] except KeyError: continue widget = zope.component.getMultiAdapter( (field_, self.widget.request), interfaces.IFieldWidget) converter = zope.component.getMultiAdapter( (field_, widget), interfaces.IDataConverter) newval = converter.toFieldValue(newvalRaw) dm = zope.component.getMultiAdapter( (obj, field_), interfaces.IDataManager) oldval = dm.query() if (oldval != newval or zope.schema.interfaces.IObject.providedBy(field_)): dm.set(newval) names.append(name) if names: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( obj, zope.lifecycleevent.Attributes( self.field.schema, *names))) # Commonly the widget context is security proxied. This method, # however, should return a bare object, so let's remove the # security proxy now that all fields have been set using the security # mechanism. return removeSecurityProxy(obj) @zope.interface.implementer(interfaces.IObjectWidget) class ObjectWidget(widget.Widget): _mode = interfaces.INPUT_MODE _value = interfaces.NO_VALUE _updating = False prefix = '' widgets = None def createObject(self, value): # keep value passed, maybe some subclasses want it # value here is the raw extracted from the widget's subform # in the form of a dict key:fieldname, value:fieldvalue name = getIfName(self.field.schema) creator = zope.component.queryMultiAdapter( (self.context, self.request, self.form, self), interfaces.IObjectFactory, name=name) if creator: obj = creator(value) else: # raise RuntimeError, that won't be swallowed raise RuntimeError( "No IObjectFactory adapter registered for %s" % name) return obj def getObject(self, value): if value.originalValue is ObjectWidget_NO_VALUE: # if the originalValue did not survive the roundtrip if self.ignoreContext: obj = self.createObject(value) else: # try to get the original object from the context.field_name dm = zope.component.getMultiAdapter( (self.context, self.field), interfaces.IDataManager) try: obj = dm.get() except KeyError: obj = self.createObject(value) except AttributeError: obj = self.createObject(value) else: # reuse the object that we got in toWidgetValue obj = value.originalValue if obj is None or obj == self.field.missing_value: # if still None, create one, otherwise following will burp obj = self.createObject(value) return obj @property def mode(self): """This sets the subwidgets modes.""" return self._mode @mode.setter def mode(self, mode): self._mode = mode # ensure that we apply the new mode to the widgets if self.widgets: for w in self.widgets.values(): w.mode = mode def setupFields(self): self.fields = field.Fields(self.field.schema) def setupWidgets(self): self.setupFields() self.prefix = self.name self.widgets = field.FieldWidgets(self, self.request, None) self.widgets.mode = self.mode # very-very important! otherwise the update() tries to set # RAW values as field values self.widgets.ignoreContext = True self.widgets.ignoreRequest = self.ignoreRequest self.widgets.update() def updateWidgets(self, setErrors=True): if self.field is None: raise ValueError( "%r .field is None, that's a blocking point" % self) self.setupWidgets() if self._value is interfaces.NO_VALUE: # XXX: maybe readonly fields/widgets should be reset here to # widget.mode = INPUT_MODE pass for name, widget_ in self.widgets.items(): if widget_.field.readonly: widget_.mode = interfaces.INPUT_MODE widget_.update() else: rawvalue = None for name, widget_ in self.widgets.items(): if widget_.mode == interfaces.DISPLAY_MODE: if rawvalue is None: # lazy evaluation converter = zope.component.getMultiAdapter( (self.field, self), interfaces.IDataConverter) obj = self.getObject(self._value) rawvalue = converter.toWidgetValue(obj) self.applyValue(widget_, rawvalue[name]) else: try: v = self._value[name] except KeyError: pass else: self.applyValue(widget_, v) def applyValue(self, widget, value): """Validate and apply value to given widget. This method gets called on any ObjectWidget value change and is responsible for validating the given value and setup an error message. This is internal apply value and validation process is needed because nothing outside this widget does know something about our internal sub widgets. """ if value is not interfaces.NO_VALUE: try: # convert widget value to field value converter = interfaces.IDataConverter(widget) fvalue = converter.toFieldValue(value) # validate field value zope.component.getMultiAdapter( (self.context, self.request, self.form, getattr(widget, 'field', None), widget), interfaces.IValidator).validate(fvalue) # convert field value back to widget value # that will probably format the value too widget.value = converter.toWidgetValue(fvalue) except (zope.schema.ValidationError, ValueError) as error: # on exception, setup the widget error message view = zope.component.getMultiAdapter( (error, self.request, widget, widget.field, self.form, self.context), interfaces.IErrorViewSnippet) view.update() widget.error = view # set the wrong value as value despite it's wrong # we want to re-show wrong values widget.value = value def update(self): # very-very-nasty: skip raising exceptions in extract while we're # updating self._updating = True try: super().update() # create the subwidgets and set their values self.updateWidgets(setErrors=False) finally: self._updating = False @property def value(self): # value (get) cannot raise an exception, then we return insane values try: self.setErrors = True return self.extract() except MultipleErrors: value = ObjectWidgetValue() if self._value is not interfaces.NO_VALUE: # send back the original object value.originalValue = self._value.originalValue for name, widget_ in self.widgets.items(): if widget_.mode != interfaces.DISPLAY_MODE: value[name] = widget_.value return value @value.setter def value(self, value): # This invokes updateWidgets on any value change e.g. update/extract. if (not isinstance(value, ObjectWidgetValue) and value is not interfaces.NO_VALUE): value = ObjectWidgetValue(value) self._value = value # create the subwidgets and set their values self.updateWidgets() def extractRaw(self, setErrors=True): '''See interfaces.IForm''' self.widgets.setErrors = setErrors # self.widgets.ignoreRequiredOnExtract = self.ignoreRequiredOnExtract data, errors = self.widgets.extractRaw() value = ObjectWidgetValue() if self._value is not interfaces.NO_VALUE: # send back the original object value.originalValue = self._value.originalValue value.update(data) return value, errors def extract(self, default=interfaces.NO_VALUE): if self.name + '-empty-marker' in self.request: self.updateWidgets(setErrors=False) # important: widget extract MUST return RAW values # just an extractData is WRONG here value, errors = self.extractRaw(setErrors=self.setErrors) if errors: # very-very-nasty: skip raising exceptions in extract # while we're updating -- that happens when the widget # is updated and update calls extract() if self._updating: # don't rebind value, send back the original object for name, widget_ in self.widgets.items(): if widget_.mode != interfaces.DISPLAY_MODE: value[name] = widget_.value return value raise MultipleErrors(errors) return value else: return default def render(self): """See z3c.form.interfaces.IWidget.""" template = self.template if template is None: # one more discriminator than in widget.Widget template = zope.component.queryMultiAdapter( (self.context, self.request, self.form, self.field, self, makeDummyObject(self.field.schema)), IPageTemplate, name=self.mode) if template is None: return super().render() return template(self) # make dummy objects providing a given interface to support # discriminating on field.schema def makeDummyObject(iface): if iface is not None: @zope.interface.implementer(iface) class DummyObject: pass else: @zope.interface.implementer(zope.interface.Interface) class DummyObject: pass dummy = DummyObject() return dummy # special template factory that takes the field.schema into account # used by zcml.py class ObjectWidgetTemplateFactory: """Widget template factory.""" def __init__(self, filename, contentType='text/html', context=None, request=None, view=None, field=None, widget=None, schema=None): self.template = ViewPageTemplateFile( filename, content_type=contentType) zope.component.adapter( util.getSpecification(context), util.getSpecification(request), util.getSpecification(view), util.getSpecification(field), util.getSpecification(widget), util.getSpecification(schema))(self) zope.interface.implementer(IPageTemplate)(self) def __call__(self, context, request, view, field, widget, schema): return self.template # default adapters @zope.interface.implementer(interfaces.IObjectFactory) class FactoryAdapter: """Most basic-default object factory adapter""" zope.component.adapts( zope.interface.Interface, # context interfaces.IFormLayer, # request zope.interface.Interface, # form -- but can become None easily (in tests) interfaces.IWidget) # widget factory = None def __init__(self, context, request, form, widget): self.context = context self.request = request self.form = form self.widget = widget def __call__(self, value): # value is the extracted data from the form obj = self.factory() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) return obj # XXX: Probably we should offer an register factory method which allows to # use all discriminators e.g. context, request, form, widget as optional # arguments. But can probably do that later in a ZCML directive def registerFactoryAdapter(for_, klass): """register the basic FactoryAdapter for a given interface and class""" name = getIfName(for_) class temp(FactoryAdapter): factory = klass zope.component.provideAdapter(temp, name=name)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/object.py
object.py
===== Forms ===== The purpose of this package is to make development of forms as simple as possible, while still providing all the hooks to do customization at any level as required by our real-world use cases. Thus, once the system is set up with all its default registrations, it should be trivial to develop a new form. The strategy of this document is to provide the most common, and thus simplest, case first and then demonstrate the available customization options. In order to not overwhelm you with our set of well-chosen defaults, all the default component registrations have been made prior to doing those examples: >>> from z3c.form import testing >>> testing.setupFormDefaults() Note, since version 2.4.2 the IFormLayer doesn't provide IBrowserRequest anymore. This is useful if you like to use z3c.form components for other requests than the IBrowserRequest. >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> import z3c.form.interfaces >>> z3c.form.interfaces.IFormLayer.isOrExtends(IBrowserRequest) False Before we can start writing forms, we must have the content to work with: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... ... id = zope.schema.TextLine( ... title='ID', ... readonly=True, ... required=True) ... ... name = zope.schema.TextLine( ... title='Name', ... required=True) ... ... gender = zope.schema.Choice( ... title='Gender', ... values=('male', 'female'), ... required=False) ... ... age = zope.schema.Int( ... title='Age', ... description=u"The person's age.", ... min=0, ... default=20, ... required=False) ... ... @zope.interface.invariant ... def ensureIdAndNameNotEqual(person): ... if person.id == person.name: ... raise zope.interface.Invalid( ... "The id and name cannot be the same.") >>> from zope.schema.fieldproperty import FieldProperty >>> @zope.interface.implementer(IPerson) ... class Person(object): ... id = FieldProperty(IPerson['id']) ... name = FieldProperty(IPerson['name']) ... gender = FieldProperty(IPerson['gender']) ... age = FieldProperty(IPerson['age']) ... ... def __init__(self, id, name, gender=None, age=None): ... self.id = id ... self.name = name ... if gender: ... self.gender = gender ... if age: ... self.age = age ... ... def __repr__(self): ... return '<%s %r>' % (self.__class__.__name__, self.name) Okay, that should suffice for now. What's next? Well, first things first. Let's create an add form for the person. Since practice showed that the ``IAdding`` interface is overkill for most projects, the default add form of ``z3c.form`` requires you to define the creation and adding mechanism. **Note**: If it is not done, ``NotImplementedError[s]`` are raised: >>> from z3c.form.testing import TestRequest >>> from z3c.form import form, field >>> abstract = form.AddForm(None, TestRequest()) >>> abstract.create({}) Traceback (most recent call last): ... NotImplementedError >>> abstract.add(1) Traceback (most recent call last): ... NotImplementedError >>> abstract.nextURL() Traceback (most recent call last): ... NotImplementedError Thus let's now create a working add form: >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson) ... ... def create(self, data): ... return Person(**data) ... ... def add(self, object): ... self.context[object.id] = object ... ... def nextURL(self): ... return 'index.html' This is as simple as it gets. We explicitly define the pieces that are custom to every situation and let the default setup of the framework do the rest. This is intentionally similar to ``zope.formlib``, because we really like the simplicity of ``zope.formlib``'s way of dealing with the common use cases. Let's try to add a new person object to the root folder (which was created during test setup). For this add form, of course, the context is now the root folder: >>> request = TestRequest() >>> addForm = PersonAddForm(root, request) Since forms are not necessarily pages -- in fact often they are not -- they must not have a ``__call__`` method that does all the processing and rendering at once. Instead, we use the update/render pattern. Thus, we first call the ``update()`` method. >>> addForm.update() Actually a lot of things happen during this stage. Let us step through it one by one pointing out the effects. Find a widget manager and update it ----------------------------------- The default widget manager knows to look for the ``fields`` attribute in the form, since it implements ``IFieldsForm``: >>> from z3c.form import interfaces >>> interfaces.IFieldsForm.providedBy(addForm) True The widget manager is then stored in the ``widgets`` attribute as promised by the ``IForm`` interface: >>> addForm.widgets FieldWidgets([...]) The widget manager will have four widgets, one for each field: >>> list(addForm.widgets.keys()) ['id', 'name', 'gender', 'age'] When the widget manager updates itself, several sub-tasks are processed. The manager goes through each field, trying to create a fully representative widget for the field. Field Availability ~~~~~~~~~~~~~~~~~~ Just because a field is requested in the field manager, does not mean that a widget has to be created for the field. There are cases when a field declaration might be ignored. The following reasons come to mind: * No widget is created if the data are not accessible in the content. * A custom widget manager has been registered to specifically ignore a field. In our simple example, all fields will be converted to widgets. Widget Creation ~~~~~~~~~~~~~~~ During the widget creation process, several pieces of information are transferred from the field to the widget: >>> age = addForm.widgets['age'] # field.title -> age.label >>> age.label 'Age' # field.required -> age.required >>> age.required False All these values can be overridden at later stages of the updating process. Widget Value ~~~~~~~~~~~~ The next step is to determine the value that should be displayed by the widget. This value could come from three places (looked up in this order): 1. The field's default value. 2. The content object that the form is representing. 3. The request in case a form has not been submitted or an error occurred. Since we are currently building an add form and not an edit form, there is no content object to represent, so the second step is not applicable. The third step is also not applicable as we do not have anything in the request. Therefore, the value should be the field's default value, or be empty. In this case the field provides a default value: >>> age.value '20' While the default of the age field is actually the integer ``20``, the widget has converted the value to the output-ready string ``'20'`` using a data converter. Widget Mode ~~~~~~~~~~~ Now the widget manager looks at the field to determine the widget mode -- in other words whether the widget is a display or edit widget. In this case all fields are input fields: >>> age.mode 'input' Deciding which mode to use, however, might not be a trivial operation. It might depend on several factors (items listed later override earlier ones): * The global ``mode`` flag of the widget manager * The permission to the content's data value * The ``readonly`` flag in the schema field * The ``mode`` flag in the field Widget Attribute Values ~~~~~~~~~~~~~~~~~~~~~~~ As mentioned before, several widget attributes are optionally overridden when the widget updates itself: * label * required * mode Since we have no customization components registered, all of those fields will remain as set before. Find an action manager, update and execute it --------------------------------------------- After all widgets have been instantiated and the ``update()`` method has been called successfully, the actions are set up. By default, the form machinery uses the button declaration on the form to create its actions. For the add form, an add button is defined by default, so that we did not need to create our own. Thus, there should be one action: >>> len(addForm.actions) 1 The add button is an action and a widget at the same time: >>> addAction = addForm.actions['add'] >>> addAction.title 'Add' >>> addAction.value 'Add' After everything is set up, all pressed buttons are executed. Once a submitted action is detected, a special action handler adapter is used to determine the actions to take. Since the add button has not been pressed yet, no action occurred. Rendering the form ------------------ Once the update is complete we can render the form using one of two methods reder or json. If we want to generate json data to be consumed by the client all we need to do is call json():: >>> import json >>> from pprint import pprint >>> pprint(json.loads(addForm.json())) {'errors': [], 'fields': [{'error': '', 'id': 'form-widgets-id', 'label': 'ID', 'mode': 'input', 'name': 'form.widgets.id', 'required': True, 'type': 'text', 'value': ''}, {'error': '', 'id': 'form-widgets-name', 'label': 'Name', 'mode': 'input', 'name': 'form.widgets.name', 'required': True, 'type': 'text', 'value': ''}, {'error': '', 'id': 'form-widgets-gender', 'label': 'Gender', 'mode': 'input', 'name': 'form.widgets.gender', 'options': [{'content': 'No value', 'id': 'form-widgets-gender-novalue', 'selected': True, 'value': '--NOVALUE--'}, {'content': 'male', 'id': 'form-widgets-gender-0', 'selected': False, 'value': 'male'}, {'content': 'female', 'id': 'form-widgets-gender-1', 'selected': False, 'value': 'female'}], 'required': False, 'type': 'select', 'value': []}, {'error': '', 'id': 'form-widgets-age', 'label': 'Age', 'mode': 'input', 'name': 'form.widgets.age', 'required': False, 'type': 'text', 'value': '20'}], 'label': '', 'mode': 'input', 'prefix': 'form.', 'status': ''} The other way we can render the form is using the render() method. The render method requires us to specify a template, we have to do this now. We have prepared a small and very simple template as part of this example: >>> import os >>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import tests >>> def addTemplate(form): ... form.template = BoundPageTemplate( ... ViewPageTemplateFile( ... 'simple_edit.pt', os.path.dirname(tests.__file__)), form) >>> addTemplate(addForm) Let's now render the page: >>> print(addForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" selected="selected" value="--NOVALUE--">No value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> The update()/render() cycle is what happens when the form is called, i.e. when it is published: >>> print(addForm()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" selected="selected" value="--NOVALUE--">No value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Note that we don't actually call render if the response has been set to a 3xx type status code (e.g. a redirect or not modified response), since the browser would not render it anyway: >>> request.response.setStatus(304) >>> print(addForm()) Let's go back to a normal status to continue the test. >>> request.response.setStatus(200) Registering a custom event handler for the DataExtractedEvent -------------------------------------------------------------- >>> data_extracted_eventlog = [] >>> from z3c.form.events import DataExtractedEvent >>> @zope.component.adapter(DataExtractedEvent) ... def data_extracted_logger(event): ... data_extracted_eventlog.append(event) >>> zope.component.provideHandler(data_extracted_logger) Submitting an add form successfully ----------------------------------- Initially the root folder of the application is empty: >>> sorted(root) [] Let's now fill the request with all the right values so that upon submitting the form with the "Add" button, the person should be added to the root folder: >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.widgets.name': 'Stephan Richter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': '20', ... 'form.buttons.add': 'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> sorted(root) ['srichter'] >>> stephan = root['srichter'] >>> stephan.id 'srichter' >>> stephan.name 'Stephan Richter' >>> stephan.gender 'male' >>> stephan.age 20 Check, if DataExtractedEvent was thrown ----------------------------------------- >>> event = data_extracted_eventlog[0] >>> 'name' in event.data True >>> event.errors () >>> event.form <PersonAddForm object at ... Submitting an add form with invalid data ---------------------------------------- Next we try to submit the add form with the required name missing. Thus, the add form should not complete with the addition, but return with the add form pointing out the error. >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': '23', ... 'form.buttons.add': 'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() The widget manager and the widget causing the error should have an error message: >>> [(error.widget.__name__, error) for error in addForm.widgets.errors] [('name', <ErrorViewSnippet for RequiredMissing>)] >>> addForm.widgets['name'].error <ErrorViewSnippet for RequiredMissing> Check, if event was thrown: >>> event = data_extracted_eventlog[-1] >>> 'id' in event.data True >>> event.errors (<ErrorViewSnippet for RequiredMissing>,) >>> event.form <PersonAddForm object at ... Let's now render the form: >>> addTemplate(addForm) >>> print(addForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> Name: <div class="error">Required input is missing.</div> </li> </ul> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input type="text" id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="srichter" /> </div> <div class="row"> <b><div class="error">Required input is missing.</div> </b><label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">No value</option> <option id="form-widgets-gender-0" value="male" selected="selected">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="23" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Notice the errors are present in the json output of the form as well >>> import json >>> from pprint import pprint >>> pprint(json.loads(addForm.json())) {'errors': [], 'fields': [{'error': '', 'id': 'form-widgets-id', 'label': 'ID', 'mode': 'input', 'name': 'form.widgets.id', 'required': True, 'type': 'text', 'value': 'srichter'}, {'error': 'Required input is missing.', 'id': 'form-widgets-name', 'label': 'Name', 'mode': 'input', 'name': 'form.widgets.name', 'required': True, 'type': 'text', 'value': ''}, {'error': '', 'id': 'form-widgets-gender', 'label': 'Gender', 'mode': 'input', 'name': 'form.widgets.gender', 'options': [{'content': 'No value', 'id': 'form-widgets-gender-novalue', 'selected': False, 'value': '--NOVALUE--'}, {'content': 'male', 'id': 'form-widgets-gender-0', 'selected': True, 'value': 'male'}, {'content': 'female', 'id': 'form-widgets-gender-1', 'selected': False, 'value': 'female'}], 'required': False, 'type': 'select', 'value': ['male']}, {'error': '', 'id': 'form-widgets-age', 'label': 'Age', 'mode': 'input', 'name': 'form.widgets.age', 'required': False, 'type': 'text', 'value': '23'}], 'label': '', 'mode': 'input', 'prefix': 'form.', 'status': 'There were some errors.'} Note that the values of the field are now extracted from the request. Another way to receive an error is by not fulfilling the invariants of the schema. In our case, the id and name cannot be the same. So let's provoke the error now: >>> request = TestRequest(form={ ... 'form.widgets.id': 'Stephan', ... 'form.widgets.name': 'Stephan', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': '23', ... 'form.buttons.add': 'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addTemplate(addForm) >>> addForm.update() and see how the form looks like: >>> print(addForm.render()) # doctest: +NOPARSE_MARKUP <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> <div class="error">The id and name cannot be the same.</div> </li> </ul> ... </body> </html> and through as json: >>> import json >>> from pprint import pprint >>> pprint(json.loads(addForm.json())) {'errors': ['The id and name cannot be the same.'], 'fields': [{'error': '', 'id': 'form-widgets-id', 'label': 'ID', 'mode': 'input', 'name': 'form.widgets.id', 'required': True, 'type': 'text', 'value': 'Stephan'}, {'error': '', 'id': 'form-widgets-name', 'label': 'Name', 'mode': 'input', 'name': 'form.widgets.name', 'required': True, 'type': 'text', 'value': 'Stephan'}, {'error': '', 'id': 'form-widgets-gender', 'label': 'Gender', 'mode': 'input', 'name': 'form.widgets.gender', 'options': [{'content': 'No value', 'id': 'form-widgets-gender-novalue', 'selected': False, 'value': '--NOVALUE--'}, {'content': 'male', 'id': 'form-widgets-gender-0', 'selected': True, 'value': 'male'}, {'content': 'female', 'id': 'form-widgets-gender-1', 'selected': False, 'value': 'female'}], 'required': False, 'type': 'select', 'value': ['male']}, {'error': '', 'id': 'form-widgets-age', 'label': 'Age', 'mode': 'input', 'name': 'form.widgets.age', 'required': False, 'type': 'text', 'value': '23'}], 'label': '', 'mode': 'input', 'prefix': 'form.', 'status': 'There were some errors.'} Let's try to provide a negative age, which is not possible either: >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': '-5', ... 'form.buttons.add': 'Add'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> [(view.widget.label, view) for view in addForm.widgets.errors] [('Name', <ErrorViewSnippet for RequiredMissing>), ('Age', <ErrorViewSnippet for TooSmall>)] But the error message for a negative age is too generic: >>> print(addForm.widgets['age'].error.render()) <div class="error">Value is too small</div> It would be better to say that negative values are disallowed. So let's register a new error view snippet for the ``TooSmall`` error: >>> from z3c.form import error >>> class TooSmallView(error.ErrorViewSnippet): ... zope.component.adapts( ... zope.schema.interfaces.TooSmall, None, None, None, None, None) ... ... def update(self): ... super(TooSmallView, self).update() ... if self.field.min == 0: ... self.message = 'The value cannot be a negative number.' >>> zope.component.provideAdapter(TooSmallView) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> print(addForm.widgets['age'].error.render()) <div class="error">The value cannot be a negative number.</div> Note: The ``adapts()`` declaration might look strange. An error view snippet is actually a multiadapter that adapts a combination of 6 objects -- error, request, widget, field, form, content. By specifying only the error, we tell the system that we do not care about the other discriminators, which then can be anything. We could also have used ``zope.interface.Interface`` instead, which would be equivalent. Additional Form Attributes and API ---------------------------------- Since we are talking about HTML forms here, add and edit forms support all relevant FORM element attributes as attributes on the class. >>> addForm.method 'post' >>> addForm.enctype 'multipart/form-data' >>> addForm.acceptCharset >>> addForm.accept The ``action`` attribute is computed. By default it is the current URL: >>> addForm.action 'http://127.0.0.1' The name is also computed. By default it takes the prefix and removes any trailing ".". >>> addForm.name 'form' The id is computed from the name, replacing dots with hyphens. Let's set the prefix to something containing more than one final dot and check how it works. >>> addForm.prefix = 'person.form.add.' >>> addForm.id 'person-form-add' The template can then use those attributes, if it likes to. In the examples previously we set the template manually. If no template is specified, the system tries to find an adapter. Without any special configuration, there is no adapter, so rendering the form fails: >>> addForm.template = None >>> addForm.render() Traceback (most recent call last): ... ComponentLookupError: ((...), <InterfaceClass ...IPageTemplate>, '') The form module provides a simple component to create adapter factories from templates: >>> factory = form.FormTemplateFactory( ... testing.getPath('../tests/simple_edit.pt'), form=PersonAddForm) Let's register our new template-based adapter factory: >>> zope.component.provideAdapter(factory) Now the factory will be used to provide a template: >>> print(addForm.render()) # doctest: +NOPARSE_MARKUP <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... </html> Since a form can also be used as a page itself, it is callable. When you call it will invoke both the ``update()`` and ``render()`` methods: >>> print(addForm()) # doctest: +NOPARSE_MARKUP <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... </html> The form also provides a label for rendering a required info. This required info depends by default on the given requiredInfo label and if at least one field is required: >>> addForm.requiredInfo '<span class="required">*</span>&ndash; required' If we set the labelRequired to None, we do not get a requiredInfo label: >>> addForm.labelRequired = None >>> addForm.requiredInfo is None True Changing Widget Attribute Values -------------------------------- It frequently happens that a customer comes along and wants to slightly or totally change some of the text shown in forms or make optional fields required. It does not make sense to always have to adjust the schema or implement a custom schema for these use cases. With the z3c.form framework all attributes -- for which it is sensible to replace a value without touching the code -- are customizable via an attribute value adapter. To demonstrate this feature, let's change the label of the name widget from "Name" to "Full Name": >>> from z3c.form import widget >>> NameLabel = widget.StaticWidgetAttribute( ... 'Full Name', field=IPerson['name']) >>> zope.component.provideAdapter(NameLabel, name='label') When the form renders, the label has now changed: >>> addForm = PersonAddForm(root, TestRequest()) >>> addTemplate(addForm) >>> addForm.update() >>> print(testing.render(addForm, './/xmlns:div[2][@class="row"]')) # doctest: +NOPARSE_MARKUP <div class="row"> <label for="form-widgets-name">Full Name</label> <input id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" type="text" /> </div> ... Adding a "Cancel" button ------------------------ Let's say a client requests that all add forms should have a "Cancel" button. When the button is pressed, the user is forwarded to the next URL of the add form. As always, the goal is to not touch the core implementation of the code, but make those changes externally. Adding a button/action is a little bit more involved than changing a value, because you have to insert the additional action and customize the action handler. Based on your needs of flexibility, multiple approaches could be chosen. Here we demonstrate the simplest one. The first step is to create a custom action manager that always inserts a cancel action: >>> from z3c.form import button >>> class AddActions(button.ButtonActions): ... zope.component.adapts( ... interfaces.IAddForm, ... zope.interface.Interface, ... zope.interface.Interface) ... ... def update(self): ... self.form.buttons = button.Buttons( ... self.form.buttons, ... button.Button('cancel', 'Cancel')) ... super(AddActions, self).update() After registering the new action manager, >>> zope.component.provideAdapter(AddActions) the add form should display a cancel button: >>> addForm.update() >>> print(testing.render(addForm, './/xmlns:div[@class="action"]')) # doctest: +NOPARSE_MARKUP <div class="action"> <input id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> </div> <div class="action"> <input id="form-buttons-cancel" name="form.buttons.cancel" class="submit-widget button-field" value="Cancel" type="submit" /> </div> ... But showing the button does not mean it does anything. So we also need a custom action handler to handle the cancel action: >>> class AddActionHandler(button.ButtonActionHandler): ... zope.component.adapts( ... interfaces.IAddForm, ... zope.interface.Interface, ... zope.interface.Interface, ... button.ButtonAction) ... ... def __call__(self): ... if self.action.name == 'form.buttons.cancel': ... self.form._finishedAdd = True ... return ... super(AddActionHandler, self).__call__() After registering the action handler, >>> zope.component.provideAdapter(AddActionHandler) we can press the cancel button and we will be forwarded: >>> request = TestRequest(form={'form.buttons.cancel': 'Cancel'}) >>> addForm = PersonAddForm(root, request) >>> addTemplate(addForm) >>> addForm.update() >>> addForm.render() '' >>> request.response.getStatus() 302 >>> request.response.getHeader('Location') 'index.html' Eventually, we might have action managers and handlers that are much more powerful and some of the manual labor in this example would become unnecessary. Creating an Edit Form --------------------- Now that we have exhaustively covered the customization possibilities of add forms, let's create an edit form. Edit forms are even simpler than add forms, since all actions are completely automatic: >>> class PersonEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) We can use the created person from the successful addition above. >>> editForm = PersonEditForm(root['srichter'], TestRequest()) After adding a template, we can look at the form: >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget textline-field">srichter</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">No value</option> <option id="form-widgets-gender-0" value="male" selected="selected">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> As you can see, the data are being pulled in from the context for the edit form. Next we will look at the behavior when submitting the form. Failure Upon Submission of Edit Form ------------------------------------ Let's now submit the form having some invalid data. >>> request = TestRequest(form={ ... 'form.widgets.name': 'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': '-1', ... 'form.buttons.apply': 'Apply'} ... ) >>> editForm = PersonEditForm(root['srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> Age: <div class="error">The value cannot be a negative number.</div> </li> </ul> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget textline-field">srichter</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Claudia Richter" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--">No value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female" selected="selected">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <b><div class="error">The value cannot be a negative number.</div> </b><label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="-1" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Successfully Editing Content ---------------------------- Let's now resubmit the form with valid data, so the data should be updated. >>> request = TestRequest(form={ ... 'form.widgets.name': 'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': '27', ... 'form.buttons.apply': 'Apply'} ... ) >>> editForm = PersonEditForm(root['srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >Data successfully updated.</i> ... >>> stephan = root['srichter'] >>> stephan.name 'Claudia Richter' >>> stephan.gender 'female' >>> stephan.age 27 When an edit form is successfully committed, a detailed object-modified event is sent out telling the system about the changes. To see the error, let's create an event subscriber for object-modified events: >>> eventlog = [] >>> import zope.lifecycleevent >>> @zope.component.adapter(zope.lifecycleevent.ObjectModifiedEvent) ... def logEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent) Let's now submit the form again, successfully changing the age: >>> request = TestRequest(form={ ... 'form.widgets.name': 'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': '29', ... 'form.buttons.apply': 'Apply'} ... ) >>> editForm = PersonEditForm(root['srichter'], request) >>> addTemplate(editForm) >>> editForm.update() We can now look at the event: >>> event = eventlog[-1] >>> event <zope...ObjectModifiedEvent object at ...> >>> attrs = event.descriptions[0] >>> attrs.interface <InterfaceClass builtins.IPerson> >>> attrs.attributes ('age',) Successful Action with No Changes --------------------------------- When submitting the form without any changes, the form will tell you so. >>> request = TestRequest(form={ ... 'form.widgets.name': 'Claudia Richter', ... 'form.widgets.gender': ['female'], ... 'form.widgets.age': '29', ... 'form.buttons.apply': 'Apply'} ... ) >>> editForm = PersonEditForm(root['srichter'], request) >>> addTemplate(editForm) >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >No changes were applied.</i> ... Changing Status Messages ------------------------ Depending on the project, it is often desirable to change the status messages to fit the application. In ``zope.formlib`` this was hard to do, since the messages were buried within fairly complex methods that one did not want to touch. In this package all those messages are exposed as form attributes. There are three messages for the edit form: * ``formErrorsMessage`` -- Indicates that an error occurred while applying the changes. This message is also available for the add form. * ``successMessage`` -- The form data was successfully applied. * ``noChangesMessage`` -- No changes were found in the form data. Let's now change the ``noChangesMessage``: >>> editForm.noChangesMessage = 'No changes were detected in the form data.' >>> editForm.update() >>> print(testing.render(editForm, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >No changes were detected in the form data.</i> ... When even more flexibility is required within a project, one could also implement these messages as properties looking up an attribute value. However, we have found this to be a rare case. Creating Edit Forms for Dictionaries ------------------------------------ Sometimes it is not desirable to edit a class instance that implements the fields, but other types of object. A good example is the need to modify a simple dictionary, where the field names are the keys. To do that, a special data manager for dictionaries is available: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.DictionaryField) The only step the developer has to complete is to re-implement the form's ``getContent()`` method to return the dictionary: >>> personDict = {'id': 'rineichen', 'name': 'Roger Ineichen', ... 'gender': None, 'age': None} >>> class PersonDictEditForm(PersonEditForm): ... def getContent(self): ... return personDict We can now use the form as usual: >>> editForm = PersonDictEditForm(None, TestRequest()) >>> addTemplate(editForm) >>> editForm.update() >>> print(editForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <span id="form-widgets-id" class="text-widget textline-field">rineichen</span> </div> <div class="row"> <label for="form-widgets-name">Full Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Roger Ineichen" /> </div> <div class="row"> <label for="form-widgets-gender">Gender</label> <select id="form-widgets-gender" name="form.widgets.gender:list" class="select-widget choice-field" size="1"> <option id="form-widgets-gender-novalue" value="--NOVALUE--" selected="selected">No value</option> <option id="form-widgets-gender-0" value="male">male</option> <option id="form-widgets-gender-1" value="female">female</option> </select> <input name="form.widgets.gender-empty-marker" type="hidden" value="1" /> </div> <div class="row"> <label for="form-widgets-age">Age</label> <input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Note that the name displayed in the form is identical to the one in the dictionary. Let's now submit a form to ensure that the data are also written to the dictionary: >>> request = TestRequest(form={ ... 'form.widgets.name': 'Jesse Ineichen', ... 'form.widgets.gender': ['male'], ... 'form.widgets.age': '5', ... 'form.buttons.apply': 'Apply'} ... ) >>> editForm = PersonDictEditForm(None, request) >>> editForm.update() >>> len(personDict) 4 >>> personDict['age'] 5 >>> personDict['gender'] 'male' >>> personDict['id'] 'rineichen' >>> personDict['name'] 'Jesse Ineichen' Creating a Display Form ----------------------- Creating a display form is simple; just instantiate, update and render it: >>> class PersonDisplayForm(form.DisplayForm): ... fields = field.Fields(IPerson) ... template = ViewPageTemplateFile( ... 'simple_display.pt', os.path.dirname(tests.__file__)) >>> display = PersonDisplayForm(stephan, TestRequest()) >>> display.update() >>> print(display.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <div class="row"> <span id="form-widgets-id" class="text-widget textline-field">srichter</span> </div> <div class="row"> <span id="form-widgets-name" class="text-widget textline-field">Claudia Richter</span> </div> <div class="row"> <span id="form-widgets-gender" class="select-widget choice-field"><span class="selected-option">female</span></span> </div> <div class="row"> <span id="form-widgets-age" class="text-widget int-field">29</span> </div> </body> </html> Simple Form Customization ------------------------- The form exposes several of the widget manager's attributes as attributes on the form. They are: ``mode``, ``ignoreContext``, ``ignoreRequest``, and ``ignoreReadonly``. Here are the values for the display form we just created: >>> display.mode 'display' >>> display.ignoreContext False >>> display.ignoreRequest True >>> display.ignoreReadonly False These values should be equal to the ones of the widget manager: >>> display.widgets.mode 'display' >>> display.widgets.ignoreContext False >>> display.widgets.ignoreRequest True >>> display.widgets.ignoreReadonly False Now, if we change those values before updating the widgets, ... >>> display.mode = interfaces.INPUT_MODE >>> display.ignoreContext = True >>> display.ignoreRequest = False >>> display.ignoreReadonly = True ... the widget manager will have the same values after updating the widgets: >>> display.updateWidgets() >>> display.widgets.mode 'input' >>> display.widgets.ignoreContext True >>> display.widgets.ignoreRequest False >>> display.widgets.ignoreReadonly True We can also set the widget prefix when we update the widgets: >>> display.updateWidgets(prefix="person") >>> display.widgets.prefix 'person' This will affect the individual widgets' names: >>> display.widgets['id'].name 'form.person.id' To use unqualified names, we must clear both the form prefix and the widgets prefix: >>> display.prefix = "" >>> display.updateWidgets(prefix="") >>> display.widgets['id'].name 'id' Extending Forms --------------- One very common use case is to extend forms. For example, you would like to use the edit form and its defined "Apply" button, but add another button yourself. Unfortunately, just inheriting the form is not enough, because the new button and handler declarations will override the inherited ones. Let me demonstrate the problem: >>> class BaseForm(form.Form): ... fields = field.Fields(IPerson).select('name') ... ... @button.buttonAndHandler('Apply') ... def handleApply(self, action): ... print('success') >>> list(BaseForm.fields.keys()) ['name'] >>> list(BaseForm.buttons.keys()) ['apply'] >>> BaseForm.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>]> Let's now derive a form from the base form: >>> class DerivedForm(BaseForm): ... fields = field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler('Cancel') ... def handleCancel(self, action): ... print('cancel') >>> list(DerivedForm.fields.keys()) ['gender'] >>> list(DerivedForm.buttons.keys()) ['cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'cancel' 'Cancel'>>]> The obvious method to "inherit" the base form's information is to copy it over: >>> class DerivedForm(BaseForm): ... fields = BaseForm.fields.copy() ... buttons = BaseForm.buttons.copy() ... handlers = BaseForm.handlers.copy() ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler('Cancel') ... def handleCancel(self, action): ... print('cancel') >>> list(DerivedForm.fields.keys()) ['name', 'gender'] >>> list(DerivedForm.buttons.keys()) ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>, <Handler for <Button 'cancel' 'Cancel'>>]> But this is pretty clumsy. Instead, the ``form`` module provides a helper method that will do the extending for you: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler('Cancel') ... def handleCancel(self, action): ... print('cancel') >>> list(DerivedForm.fields.keys()) ['name', 'gender'] >>> list(DerivedForm.buttons.keys()) ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>, <Handler for <Button 'cancel' 'Cancel'>>]> If you, for example do not want to extend the buttons, you can turn that off: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm, ignoreButtons=True) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler('Cancel') ... def handleCancel(self, action): ... print('cancel') >>> list(DerivedForm.fields.keys()) ['name', 'gender'] >>> list(DerivedForm.buttons.keys()) ['cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'apply' 'Apply'>>, <Handler for <Button 'cancel' 'Cancel'>>]> If you, for example do not want to extend the handlers, you can turn that off: >>> class DerivedForm(BaseForm): ... form.extends(BaseForm, ignoreHandlers=True) ... ... fields += field.Fields(IPerson).select('gender') ... ... @button.buttonAndHandler('Cancel') ... def handleCancel(self, action): ... print('cancel') >>> list(DerivedForm.fields.keys()) ['name', 'gender'] >>> list(DerivedForm.buttons.keys()) ['apply', 'cancel'] >>> DerivedForm.handlers <Handlers [<Handler for <Button 'cancel' 'Cancel'>>]> Custom widget factories ----------------------- Another important part of a form is that we can use custom widgets. We can do this in a form by defining a widget factory for a field. We can get the field from the fields collection e.g. ``fields['foo']``. This means, we can define new widget factories by defining ``fields['foo'].widgetFactory = MyWidget``. Let's show a sample and define a custom widget: >>> from z3c.form.browser import text >>> class MyWidget(text.TextWidget): ... """My new widget.""" ... klass = 'MyCSS' Now we can define a field widget factory: >>> def MyFieldWidget(field, request): ... """IFieldWidget factory for MyWidget.""" ... return widget.FieldWidget(field, MyWidget(request)) We register the ``MyWidget`` in a form like: >>> class MyEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) ... fields['name'].widgetFactory = MyFieldWidget We can see that the custom widget gets used in the rendered form: >>> myEdit = MyEditForm(root['srichter'], TestRequest()) >>> addTemplate(myEdit) >>> myEdit.update() >>> print(testing.render(myEdit, './/xmlns:input[@id="form-widgets-name"]')) <input type="text" id="form-widgets-name" name="form.widgets.name" class="MyCSS required textline-field" value="Claudia Richter" /> Hidden fields ------------- Another important part of a form is that we can generate hidden widgets. We can do this in a form by defining a widget mode. We can do this by override the setUpWidgets method. >>> class HiddenFieldEditForm(form.EditForm): ... ... fields = field.Fields(IPerson) ... fields['name'].widgetFactory = MyFieldWidget ... ... def updateWidgets(self): ... super(HiddenFieldEditForm, self).updateWidgets() ... self.widgets['age'].mode = interfaces.HIDDEN_MODE We can see that the widget gets rendered as hidden: >>> hiddenEdit = HiddenFieldEditForm(root['srichter'], TestRequest()) >>> addTemplate(hiddenEdit) >>> hiddenEdit.update() >>> print(testing.render(hiddenEdit, './/xmlns:input[@id="form-widgets-age"]')) <input type="hidden" id="form-widgets-age" name="form.widgets.age" class="hidden-widget" value="29" /> Actions with Errors ------------------- Even though the data might be validated correctly, it sometimes happens that data turns out to be invalid while the action is executed. In those cases a special action execution error can be raised that wraps the original error. >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson).select('id') ... ... @button.buttonAndHandler('Check') ... def handleCheck(self, action): ... data, errors = self.extractData() ... if data['id'] in self.getContent(): ... raise interfaces.WidgetActionExecutionError( ... 'id', zope.interface.Invalid('Id already exists')) In this case the action execution error is specific to a widget. The framework will attach a proper error view to the widget and the widget manager: >>> request = TestRequest(form={ ... 'form.widgets.id': 'srichter', ... 'form.buttons.check': 'Check'} ... ) >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> addForm.widgets.errors (<InvalidErrorViewSnippet for Invalid>,) >>> addForm.widgets['id'].error <InvalidErrorViewSnippet for Invalid> >>> addForm.status 'There were some errors.' If the error is non-widget specific, then we can simply use the generic action execution error: >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson).select('id') ... ... @button.buttonAndHandler('Check') ... def handleCheck(self, action): ... raise interfaces.ActionExecutionError( ... zope.interface.Invalid('Some problem occurred.')) Let's have a look at the result: >>> addForm = PersonAddForm(root, request) >>> addForm.update() >>> addForm.widgets.errors (<InvalidErrorViewSnippet for Invalid>,) >>> addForm.status 'There were some errors.' **Note**: The action execution errors are connected to the form via an event listener called ``handlerActionError``. This event listener listens for ``IActionErrorEvent`` events. If the event is called for an action associated with a form, the listener does its work as seen above. If the action is not coupled to a form, then event listener does nothing: >>> from z3c.form import action >>> cancel = action.Action(request, 'Cancel') >>> event = action.ActionErrorOccurred(cancel, ValueError(3)) >>> form.handleActionError(event) Applying Changes ---------------- When applying the data of a form to a content component, the function ``applyChanges()`` is called. It simply iterates through the fields of the form and uses the data managers to store the values. The output of the function is a list of changes: >>> roger = Person('roger', 'Roger') >>> roger <Person 'Roger'> >>> class BaseForm(form.Form): ... fields = field.Fields(IPerson).select('name') >>> myForm = BaseForm(roger, TestRequest()) >>> form.applyChanges(myForm, roger, {'name': 'Roger Ineichen'}) {<InterfaceClass builtins.IPerson>: ['name']} >>> roger <Person 'Roger Ineichen'> When a field is missing from the data, it is simply skipped: >>> form.applyChanges(myForm, roger, {}) {} If the new and old value are identical, storing the data is skipped as well: >>> form.applyChanges(myForm, roger, {'name': 'Roger Ineichen'}) {} In some cases the data converter for a field-widget pair returns the ``NOT_CHANGED`` value. In this case, the field is skipped as well: >>> form.applyChanges(myForm, roger, {'name': interfaces.NOT_CHANGED}) {} >>> roger <Person 'Roger Ineichen'> Refreshing actions ------------------ Sometimes, it's useful to update actions again after executing them, because some conditions could have changed. For example, imagine we have a sequence edit form that has a delete button. We don't want to show delete button when the sequence is empty. The button condition would handle this, but what if the sequence becomes empty as a result of execution of the delete action that was available? In that case we want to refresh our actions to new conditions to make our delete button not visible anymore. The ``refreshActions`` form variable is intended to handle this case. Let's create a simple form with an action that clears our context sequence. >>> class SequenceForm(form.Form): ... ... @button.buttonAndHandler('Empty', condition=lambda form:bool(form.context)) ... def handleEmpty(self, action): ... self.context[:] = [] ... self.refreshActions = True First, let's illustrate simple cases, when no button is pressed. The button will be available when context is not empty. >>> context = [1, 2, 3, 4] >>> request = TestRequest() >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:div[@class="action"]')) # doctest: +NOPARSE_MARKUP <div class="action"> <input id="form-buttons-empty" name="form.buttons.empty" class="submit-widget button-field" value="Empty" type="submit" /> </div> ... The button will not be available when the context is empty. >>> context = [] >>> request = TestRequest() >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:form')) <form action="."> </form> Now, the most interesting case when context is not empty, but becomes empty as a result of pressing the "empty" button. We set the ``refreshActions`` flag in the action handler, so our actions should be updated to new conditions. >>> context = [1, 2, 3, 4, 5] >>> request = TestRequest(form={ ... 'form.buttons.empty': 'Empty'} ... ) >>> myForm = SequenceForm(context, request) >>> myForm.update() >>> addTemplate(myForm) >>> print(testing.render(myForm, './/xmlns:form')) <form action="."> </form> Integration tests ----------------- Identifying the different forms can be important if it comes to layout template lookup. Let's ensure that we support the right interfaces for the different forms. Form ~~~~ >>> from zope.interface.verify import verifyObject >>> from z3c.form import interfaces >>> obj = form.Form(None, None) >>> verifyObject(interfaces.IForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False DisplayForm ~~~~~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.DisplayForm(None, None) >>> verifyObject(interfaces.IDisplayForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False EditForm ~~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.EditForm(None, None) >>> verifyObject(interfaces.IEditForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) False AddForm ~~~~~~~ >>> from z3c.form import interfaces >>> obj = form.AddForm(None, None) >>> verifyObject(interfaces.IAddForm, obj) True >>> interfaces.IForm.providedBy(obj) True >>> from z3c.form import interfaces >>> interfaces.IDisplayForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IEditForm.providedBy(obj) False >>> from z3c.form import interfaces >>> interfaces.IAddForm.providedBy(obj) True
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/form.rst
form.rst
__docformat__ = "reStructuredText" import zope.component import zope.event from zope.interface import implementer from z3c.form import form from z3c.form import interfaces from z3c.form.events import DataExtractedEvent @implementer(interfaces.IGroup) class Group(form.BaseForm): groups = () def __init__(self, context, request, parentForm): self.context = context self.request = request self.parentForm = self.__parent__ = parentForm def updateWidgets(self, prefix=None): '''See interfaces.IForm''' self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), interfaces.IWidgets) for attrName in ('mode', 'ignoreRequest', 'ignoreContext', 'ignoreReadonly'): value = getattr(self.parentForm.widgets, attrName) setattr(self.widgets, attrName, value) if prefix is not None: self.widgets.prefix = prefix self.widgets.update() def update(self): '''See interfaces.IForm''' self.updateWidgets() groups = [] for groupClass in self.groups: # only instantiate the groupClass if it hasn't already # been instantiated if interfaces.IGroup.providedBy(groupClass): group = groupClass else: group = groupClass(self.context, self.request, self) group.update() groups.append(group) self.groups = tuple(groups) def extractData(self, setErrors=True): '''See interfaces.IForm''' data, errors = super().extractData(setErrors=setErrors) for group in self.groups: groupData, groupErrors = group.extractData(setErrors=setErrors) data.update(groupData) if groupErrors: if errors: errors += groupErrors else: errors = groupErrors zope.event.notify(DataExtractedEvent(data, errors, self)) return data, errors def applyChanges(self, data): '''See interfaces.IEditForm''' content = self.getContent() changed = form.applyChanges(self, content, data) for group in self.groups: groupChanged = group.applyChanges(data) for interface, names in groupChanged.items(): changed[interface] = changed.get(interface, []) + names return changed @implementer(interfaces.IGroupForm) class GroupForm: """A mix-in class for add and edit forms to support groups.""" groups = () def extractData(self, setErrors=True): '''See interfaces.IForm''' data, errors = super().extractData(setErrors=setErrors) for group in self.groups: groupData, groupErrors = group.extractData(setErrors=setErrors) data.update(groupData) if groupErrors: if errors: errors += groupErrors else: errors = groupErrors zope.event.notify(DataExtractedEvent(data, errors, self)) return data, errors def applyChanges(self, data): '''See interfaces.IEditForm''' descriptions = [] content = self.getContent() changed = form.applyChanges(self, content, data) for group in self.groups: groupChanged = group.applyChanges(data) for interface, names in groupChanged.items(): changed[interface] = changed.get(interface, []) + names if changed: for interface, names in changed.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( content, *descriptions)) return changed def update(self): '''See interfaces.IForm''' self.updateWidgets() groups = [] for groupClass in self.groups: # only instantiate the groupClass if it hasn't already # been instantiated if interfaces.IGroup.providedBy(groupClass): group = groupClass else: group = groupClass(self.context, self.request, self) group.update() groups.append(group) self.groups = tuple(groups) self.updateActions() self.actions.execute()
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/group.py
group.py
=========== Group Forms =========== Group forms allow you to split up a form into several logical units without much overhead. To the parent form, groups should be only dealt with during coding and be transparent on the data extraction level. For the examples to work, we have to bring up most of the form framework: >>> from z3c.form import testing >>> testing.setupFormDefaults() So let's first define a complex content component that warrants setting up multiple groups: >>> import zope.interface >>> import zope.schema >>> class IVehicleRegistration(zope.interface.Interface): ... firstName = zope.schema.TextLine(title='First Name') ... lastName = zope.schema.TextLine(title='Last Name') ... ... license = zope.schema.TextLine(title='License') ... address = zope.schema.TextLine(title='Address') ... ... model = zope.schema.TextLine(title='Model') ... make = zope.schema.TextLine(title='Make') ... year = zope.schema.TextLine(title='Year') >>> @zope.interface.implementer(IVehicleRegistration) ... class VehicleRegistration(object): ... ... def __init__(self, **kw): ... for name, value in kw.items(): ... setattr(self, name, value) The schema above can be separated into basic, license, and car information, where the latter two will be placed into groups. First we create the two groups: >>> from z3c.form import field, group >>> class LicenseGroup(group.Group): ... label = 'License' ... fields = field.Fields(IVehicleRegistration).select( ... 'license', 'address') >>> class CarGroup(group.Group): ... label = 'Car' ... fields = field.Fields(IVehicleRegistration).select( ... 'model', 'make', 'year') Most of the group is setup like any other (sub)form. Additionally, you can specify a label, which is a human-readable string that can be used for layout purposes. Let's now create an add form for the entire vehicle registration. In comparison to a regular add form, you only need to add the ``GroupForm`` as one of the base classes. The groups are specified in a simple tuple: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import form, tests >>> class RegistrationAddForm(group.GroupForm, form.AddForm): ... fields = field.Fields(IVehicleRegistration).select( ... 'firstName', 'lastName') ... groups = (LicenseGroup, CarGroup) ... ... template = ViewPageTemplateFile( ... 'simple_groupedit.pt', os.path.dirname(tests.__file__)) ... ... def create(self, data): ... return VehicleRegistration(**data) ... ... def add(self, object): ... self.getContent()['obj1'] = object ... return object Note: The order of the base classes is very important here. The ``GroupForm`` class must be left of the ``AddForm`` class, because the ``GroupForm`` class overrides some methods of the ``AddForm`` class. Now we can instantiate the form: >>> request = testing.TestRequest() >>> add = RegistrationAddForm(None, request) >>> add.update() After the form is updated the tuple of group classes is converted to group instances: >>> add.groups (<LicenseGroup object at ...>, <CarGroup object at ...>) If we happen to update the add form again, the groups that have already been converted to instances ares skipped. >>> add.update() >>> add.groups (<LicenseGroup object at ...>, <CarGroup object at ...>) We can now render the form: >>> print(add.render()) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-firstName">First Name</label> <input type="text" id="form-widgets-firstName" name="form.widgets.firstName" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-lastName">Last Name</label> <input type="text" id="form-widgets-lastName" name="form.widgets.lastName" class="text-widget required textline-field" value="" /> </div> <fieldset> <legend>License</legend> <div class="row"> <label for="form-widgets-license">License</label> <input type="text" id="form-widgets-license" name="form.widgets.license" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-address">Address</label> <input type="text" id="form-widgets-address" name="form.widgets.address" class="text-widget required textline-field" value="" /> </div> </fieldset> <fieldset> <legend>Car</legend> <div class="row"> <label for="form-widgets-model">Model</label> <input type="text" id="form-widgets-model" name="form.widgets.model" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-make">Make</label> <input type="text" id="form-widgets-make" name="form.widgets.make" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="form-widgets-year">Year</label> <input type="text" id="form-widgets-year" name="form.widgets.year" class="text-widget required textline-field" value="" /> </div> </fieldset> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Registering a custom event handler for the DataExtractedEvent -------------------------------------------------------------- >>> data_extracted_eventlog = [] >>> from z3c.form.events import DataExtractedEvent >>> @zope.component.adapter(DataExtractedEvent) ... def data_extracted_logger(event): ... data_extracted_eventlog.append(event) >>> zope.component.provideHandler(data_extracted_logger) Let's now submit the form, but forgetting to enter the address: >>> request = testing.TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter', ... 'form.widgets.license': 'MA 40387', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.add': 'Add' ... }) >>> add = RegistrationAddForm(None, request) >>> add.update() >>> print(testing.render(add, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >There were some errors.</i> ... >>> print(testing.render(add, './/xmlns:fieldset[1]/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Address: <div class="error">Required input is missing.</div> </li> </ul> ... As you can see, the template is clever enough to just report the errors at the top of the form, but still report the actual problem within the group. Check, if DataExtractedEvent was thrown: >>> len(data_extracted_eventlog) > 0 True So what happens, if errors happen inside and outside a group? >>> request = testing.TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.license': 'MA 40387', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.add': 'Add' ... }) >>> add = RegistrationAddForm(None, request) >>> add.update() >>> print(testing.render(add, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >There were some errors.</i> ... >>> print(testing.render(add, './/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Last Name: <div class="error">Required input is missing.</div> </li> </ul> ... <ul > <li> Address: <div class="error">Required input is missing.</div> </li> </ul> ... >>> print(testing.render(add, './/xmlns:fieldset[1]/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Address: <div class="error">Required input is missing.</div> </li> </ul> ... Let's now successfully complete the add form. >>> from zope.container import btree >>> context = btree.BTreeContainer() >>> request = testing.TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter', ... 'form.widgets.license': 'MA 40387', ... 'form.widgets.address': '10 Main St, Maynard, MA', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.add': 'Add' ... }) >>> add = RegistrationAddForm(context, request) >>> add.update() The object is now added to the container and all attributes should be set: >>> reg = context['obj1'] >>> reg.firstName 'Stephan' >>> reg.lastName 'Richter' >>> reg.license 'MA 40387' >>> reg.address '10 Main St, Maynard, MA' >>> reg.model 'BMW' >>> reg.make '325' >>> reg.year '2005' Let's now have a look at an edit form for the vehicle registration: >>> class RegistrationEditForm(group.GroupForm, form.EditForm): ... fields = field.Fields(IVehicleRegistration).select( ... 'firstName', 'lastName') ... groups = (LicenseGroup, CarGroup) ... ... template = ViewPageTemplateFile( ... 'simple_groupedit.pt', os.path.dirname(tests.__file__)) >>> request = testing.TestRequest() >>> edit = RegistrationEditForm(reg, request) >>> edit.update() After updating the form, we can render the HTML: >>> print(edit.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-firstName">First Name</label> <input type="text" id="form-widgets-firstName" name="form.widgets.firstName" class="text-widget required textline-field" value="Stephan" /> </div> <div class="row"> <label for="form-widgets-lastName">Last Name</label> <input type="text" id="form-widgets-lastName" name="form.widgets.lastName" class="text-widget required textline-field" value="Richter" /> </div> <fieldset> <legend>License</legend> <div class="row"> <label for="form-widgets-license">License</label> <input type="text" id="form-widgets-license" name="form.widgets.license" class="text-widget required textline-field" value="MA 40387" /> </div> <div class="row"> <label for="form-widgets-address">Address</label> <input type="text" id="form-widgets-address" name="form.widgets.address" class="text-widget required textline-field" value="10 Main St, Maynard, MA" /> </div> </fieldset> <fieldset> <legend>Car</legend> <div class="row"> <label for="form-widgets-model">Model</label> <input type="text" id="form-widgets-model" name="form.widgets.model" class="text-widget required textline-field" value="BMW" /> </div> <div class="row"> <label for="form-widgets-make">Make</label> <input type="text" id="form-widgets-make" name="form.widgets.make" class="text-widget required textline-field" value="325" /> </div> <div class="row"> <label for="form-widgets-year">Year</label> <input type="text" id="form-widgets-year" name="form.widgets.year" class="text-widget required textline-field" value="2005" /> </div> </fieldset> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> The behavior when an error occurs is identical to that of the add form: >>> request = testing.TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter', ... 'form.widgets.license': 'MA 40387', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> edit.update() >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >There were some errors.</i> ... >>> print(testing.render(edit, './/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Address: <div class="error">Required input is missing.</div> </li> </ul> ... >>> print(testing.render(edit, './/xmlns:fieldset/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Address: <div class="error">Required input is missing.</div> </li> </ul> ... When an edit form with groups is successfully committed, a detailed object-modified event is sent out telling the system about the changes. To see the error, let's create an event subscriber for object-modified events: >>> eventlog = [] >>> import zope.lifecycleevent >>> @zope.component.adapter(zope.lifecycleevent.ObjectModifiedEvent) ... def logEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent) Let's now complete the form successfully: >>> request = testing.TestRequest(form={ ... 'form.widgets.firstName': 'Stephan', ... 'form.widgets.lastName': 'Richter', ... 'form.widgets.license': 'MA 4038765', ... 'form.widgets.address': '11 Main St, Maynard, MA', ... 'form.widgets.model': 'Ford', ... 'form.widgets.make': 'F150', ... 'form.widgets.year': '2006', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> edit.update() The success message will be shown on the form, ... >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >Data successfully updated.</i> ... and the data are correctly updated: >>> reg.firstName 'Stephan' >>> reg.lastName 'Richter' >>> reg.license 'MA 4038765' >>> reg.address '11 Main St, Maynard, MA' >>> reg.model 'Ford' >>> reg.make 'F150' >>> reg.year '2006' Let's look at the event: >>> event = eventlog[-1] >>> event <zope...ObjectModifiedEvent object at ...> The event's description contains the changed Interface and the names of all changed fields, even if they where in different groups: >>> attrs = event.descriptions[0] >>> attrs.interface <InterfaceClass builtins.IVehicleRegistration> >>> attrs.attributes ('license', 'address', 'model', 'make', 'year') Group form as instance ---------------------- It is also possible to use group instances in forms. Let's setup our previous form and assing a group instance: >>> class RegistrationEditForm(group.GroupForm, form.EditForm): ... fields = field.Fields(IVehicleRegistration).select( ... 'firstName', 'lastName') ... ... template = ViewPageTemplateFile( ... 'simple_groupedit.pt', os.path.dirname(tests.__file__)) >>> request = testing.TestRequest() >>> edit = RegistrationEditForm(reg, request) Instanciate the form and use a group class and a group instance: >>> carGroupInstance = CarGroup(edit.context, request, edit) >>> edit.groups = (LicenseGroup, carGroupInstance) >>> edit.update() >>> print(edit.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-firstName">First Name</label> <input id="form-widgets-firstName" name="form.widgets.firstName" class="text-widget required textline-field" value="Stephan" type="text" /> </div> <div class="row"> <label for="form-widgets-lastName">Last Name</label> <input id="form-widgets-lastName" name="form.widgets.lastName" class="text-widget required textline-field" value="Richter" type="text" /> </div> <fieldset> <legend>License</legend> <div class="row"> <label for="form-widgets-license">License</label> <input id="form-widgets-license" name="form.widgets.license" class="text-widget required textline-field" value="MA 4038765" type="text" /> </div> <div class="row"> <label for="form-widgets-address">Address</label> <input id="form-widgets-address" name="form.widgets.address" class="text-widget required textline-field" value="11 Main St, Maynard, MA" type="text" /> </div> </fieldset> <fieldset> <legend>Car</legend> <div class="row"> <label for="form-widgets-model">Model</label> <input id="form-widgets-model" name="form.widgets.model" class="text-widget required textline-field" value="Ford" type="text" /> </div> <div class="row"> <label for="form-widgets-make">Make</label> <input id="form-widgets-make" name="form.widgets.make" class="text-widget required textline-field" value="F150" type="text" /> </div> <div class="row"> <label for="form-widgets-year">Year</label> <input id="form-widgets-year" name="form.widgets.year" class="text-widget required textline-field" value="2006" type="text" /> </div> </fieldset> <div class="action"> <input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" /> </div> </form> </body> </html> Groups with Different Content ----------------------------- You can customize the content for a group by overriding a group's ``getContent`` method. This is a very easy way to get around not having object widgets. For example, suppose we want to maintain the vehicle owner's information in a separate class than the vehicle. We might have an ``IVehicleOwner`` interface like so. >>> class IVehicleOwner(zope.interface.Interface): ... firstName = zope.schema.TextLine(title='First Name') ... lastName = zope.schema.TextLine(title='Last Name') Then out ``IVehicleRegistration`` interface would include an object field for the owner instead of the ``firstName`` and ``lastName`` fields. >>> class IVehicleRegistration(zope.interface.Interface): ... owner = zope.schema.Object(title='Owner', schema=IVehicleOwner) ... ... license = zope.schema.TextLine(title='License') ... address = zope.schema.TextLine(title='Address') ... ... model = zope.schema.TextLine(title='Model') ... make = zope.schema.TextLine(title='Make') ... year = zope.schema.TextLine(title='Year') Now let's create simple implementations of these two interfaces. >>> @zope.interface.implementer(IVehicleOwner) ... class VehicleOwner(object): ... ... def __init__(self, **kw): ... for name, value in kw.items(): ... setattr(self, name, value) >>> @zope.interface.implementer(IVehicleRegistration) ... class VehicleRegistration(object): ... ... def __init__(self, **kw): ... for name, value in kw.items(): ... setattr(self, name, value) Now we can create a group just for the owner with its own ``getContent`` method that simply returns the ``owner`` object field of the ``VehicleRegistration`` instance. >>> class OwnerGroup(group.Group): ... label = 'Owner' ... fields = field.Fields(IVehicleOwner, prefix='owner') ... ... def getContent(self): ... return self.context.owner When we create an Edit form for example, we should omit the ``owner`` field which is taken care of with the group. >>> class RegistrationEditForm(group.GroupForm, form.EditForm): ... fields = field.Fields(IVehicleRegistration).omit( ... 'owner') ... groups = (OwnerGroup,) ... ... template = ViewPageTemplateFile( ... 'simple_groupedit.pt', os.path.dirname(tests.__file__)) >>> reg = VehicleRegistration( ... license='MA 40387', ... address='10 Main St, Maynard, MA', ... model='BMW', ... make='325', ... year='2005', ... owner=VehicleOwner(firstName='Stephan', ... lastName='Richter')) >>> request = testing.TestRequest() >>> edit = RegistrationEditForm(reg, request) >>> edit.update() When we render the form, the group appears as we would expect but with the ``owner`` prefix for the fields. >>> print(edit.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-license">License</label> <input type="text" id="form-widgets-license" name="form.widgets.license" class="text-widget required textline-field" value="MA 40387" /> </div> <div class="row"> <label for="form-widgets-address">Address</label> <input type="text" id="form-widgets-address" name="form.widgets.address" class="text-widget required textline-field" value="10 Main St, Maynard, MA" /> </div> <div class="row"> <label for="form-widgets-model">Model</label> <input type="text" id="form-widgets-model" name="form.widgets.model" class="text-widget required textline-field" value="BMW" /> </div> <div class="row"> <label for="form-widgets-make">Make</label> <input type="text" id="form-widgets-make" name="form.widgets.make" class="text-widget required textline-field" value="325" /> </div> <div class="row"> <label for="form-widgets-year">Year</label> <input type="text" id="form-widgets-year" name="form.widgets.year" class="text-widget required textline-field" value="2005" /> </div> <fieldset> <legend>Owner</legend> <div class="row"> <label for="form-widgets-owner-firstName">First Name</label> <input type="text" id="form-widgets-owner-firstName" name="form.widgets.owner.firstName" class="text-widget required textline-field" value="Stephan" /> </div> <div class="row"> <label for="form-widgets-owner-lastName">Last Name</label> <input type="text" id="form-widgets-owner-lastName" name="form.widgets.owner.lastName" class="text-widget required textline-field" value="Richter" /> </div> </fieldset> <div class="action"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Now let's try and edit the owner. For example, suppose that Stephan Richter gave his BMW to Paul Carduner because he is such a nice guy. >>> request = testing.TestRequest(form={ ... 'form.widgets.owner.firstName': 'Paul', ... 'form.widgets.owner.lastName': 'Carduner', ... 'form.widgets.license': 'MA 4038765', ... 'form.widgets.address': 'Berkeley', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> edit.update() We'll see if everything worked on the form side. >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >Data successfully updated.</i> ... Now the owner object should have updated fields. >>> reg.owner.firstName 'Paul' >>> reg.owner.lastName 'Carduner' >>> reg.license 'MA 4038765' >>> reg.address 'Berkeley' >>> reg.model 'BMW' >>> reg.make '325' >>> reg.year '2005' Nested Groups ------------- The group can contains groups. Let's adapt the previous RegistrationEditForm: >>> class OwnerGroup(group.Group): ... label = 'Owner' ... fields = field.Fields(IVehicleOwner, prefix='owner') ... ... def getContent(self): ... return self.context.owner >>> class VehicleRegistrationGroup(group.Group): ... label = 'Registration' ... fields = field.Fields(IVehicleRegistration).omit( ... 'owner') ... groups = (OwnerGroup,) ... ... template = ViewPageTemplateFile( ... 'simple_groupedit.pt', os.path.dirname(tests.__file__)) >>> class RegistrationEditForm(group.GroupForm, form.EditForm): ... groups = (VehicleRegistrationGroup,) ... ... template = ViewPageTemplateFile( ... 'simple_nested_groupedit.pt', os.path.dirname(tests.__file__)) >>> reg = VehicleRegistration( ... license='MA 40387', ... address='10 Main St, Maynard, MA', ... model='BMW', ... make='325', ... year='2005', ... owner=VehicleOwner(firstName='Stephan', ... lastName='Richter')) >>> request = testing.TestRequest() >>> edit = RegistrationEditForm(reg, request) >>> edit.update() Now let's try and edit the owner. For example, suppose that Stephan Richter gave his BMW to Paul Carduner because he is such a nice guy. >>> request = testing.TestRequest(form={ ... 'form.widgets.owner.firstName': 'Paul', ... 'form.widgets.owner.lastName': 'Carduner', ... 'form.widgets.license': 'MA 4038765', ... 'form.widgets.address': 'Berkeley', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> edit.update() We'll see if everything worked on the form side. >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >Data successfully updated.</i> ... Now the owner object should have updated fields. >>> reg.owner.firstName 'Paul' >>> reg.owner.lastName 'Carduner' >>> reg.license 'MA 4038765' >>> reg.address 'Berkeley' >>> reg.model 'BMW' >>> reg.make '325' >>> reg.year '2005' So what happens, if errors happen inside a nested group? Let's use an empty invalid object for the test missing input errors: >>> reg = VehicleRegistration(owner=VehicleOwner()) >>> request = testing.TestRequest(form={ ... 'form.widgets.owner.firstName': '', ... 'form.widgets.owner.lastName': '', ... 'form.widgets.license': '', ... 'form.widgets.address': '', ... 'form.widgets.model': '', ... 'form.widgets.make': '', ... 'form.widgets.year': '', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> edit.update() >>> data, errors = edit.extractData() >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >There were some errors.</i> ... >>> print(testing.render(edit, './/xmlns:fieldset/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> License: <div class="error">Required input is missing.</div> </li> <li> Address: <div class="error">Required input is missing.</div> </li> <li> Model: <div class="error">Required input is missing.</div> </li> <li> Make: <div class="error">Required input is missing.</div> </li> <li> Year: <div class="error">Required input is missing.</div> </li> </ul> ... <ul > <li> First Name: <div class="error">Required input is missing.</div> </li> <li> Last Name: <div class="error">Required input is missing.</div> </li> </ul> ... Group instance in nested group ------------------------------ Let's also test if the Group class can handle group objects as instances: >>> reg = VehicleRegistration( ... license='MA 40387', ... address='10 Main St, Maynard, MA', ... model='BMW', ... make='325', ... year='2005', ... owner=VehicleOwner(firstName='Stephan', ... lastName='Richter')) >>> request = testing.TestRequest() >>> edit = RegistrationEditForm(reg, request) >>> vrg = VehicleRegistrationGroup(edit.context, request, edit) >>> ownerGroup = OwnerGroup(edit.context, request, edit) Now build the group instance object chain: >>> vrg.groups = (ownerGroup,) >>> edit.groups = (vrg,) Also use refreshActions which is not needed but will make coverage this additional line of code in the update method: >>> edit.refreshActions = True Update and render: >>> edit.update() >>> print(edit.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <fieldset> <legend>Registration</legend> <div class="row"> <label for="form-widgets-license">License</label> <input id="form-widgets-license" name="form.widgets.license" class="text-widget required textline-field" value="MA 40387" type="text" /> </div> <div class="row"> <label for="form-widgets-address">Address</label> <input id="form-widgets-address" name="form.widgets.address" class="text-widget required textline-field" value="10 Main St, Maynard, MA" type="text" /> </div> <div class="row"> <label for="form-widgets-model">Model</label> <input id="form-widgets-model" name="form.widgets.model" class="text-widget required textline-field" value="BMW" type="text" /> </div> <div class="row"> <label for="form-widgets-make">Make</label> <input id="form-widgets-make" name="form.widgets.make" class="text-widget required textline-field" value="325" type="text" /> </div> <div class="row"> <label for="form-widgets-year">Year</label> <input id="form-widgets-year" name="form.widgets.year" class="text-widget required textline-field" value="2005" type="text" /> </div> <fieldset> <legend>Owner</legend> <div class="row"> <label for="form-widgets-owner-firstName">First Name</label> <input id="form-widgets-owner-firstName" name="form.widgets.owner.firstName" class="text-widget required textline-field" value="Stephan" type="text" /> </div> <div class="row"> <label for="form-widgets-owner-lastName">Last Name</label> <input id="form-widgets-owner-lastName" name="form.widgets.owner.lastName" class="text-widget required textline-field" value="Richter" type="text" /> </div> </fieldset> </fieldset> <div class="action"> <input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" /> </div> </form> </body> </html> Now test the error handling if just one missing value is given in a group: >>> request = testing.TestRequest(form={ ... 'form.widgets.owner.firstName': 'Paul', ... 'form.widgets.owner.lastName': '', ... 'form.widgets.license': 'MA 4038765', ... 'form.widgets.address': 'Berkeley', ... 'form.widgets.model': 'BMW', ... 'form.widgets.make': '325', ... 'form.widgets.year': '2005', ... 'form.buttons.apply': 'Apply' ... }) >>> edit = RegistrationEditForm(reg, request) >>> vrg = VehicleRegistrationGroup(edit.context, request, edit) >>> ownerGroup = OwnerGroup(edit.context, request, edit) >>> vrg.groups = (ownerGroup,) >>> edit.groups = (vrg,) >>> edit.update() >>> data, errors = edit.extractData() >>> print(testing.render(edit, './/xmlns:i')) # doctest: +NOPARSE_MARKUP <i >There were some errors.</i> ... >>> print(testing.render(edit, './/xmlns:fieldset/xmlns:ul')) # doctest: +NOPARSE_MARKUP <ul > <li> Last Name: <div class="error">Required input is missing.</div> </li> </ul> ... Just check whether we fully support the interface: >>> from z3c.form import interfaces >>> from zope.interface.verify import verifyClass >>> verifyClass(interfaces.IGroup, group.Group) True
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/group.rst
group.rst
import zope.component import zope.interface import zope.location from zope.contentprovider.interfaces import IContentProvider from z3c.form import interfaces from z3c.form.error import MultipleErrors from z3c.form.field import FieldWidgets from z3c.form.interfaces import IContentProviders class BaseProvider: __slots__ = ('position') lookup_ = BaseProvider() @zope.interface.implementer(IContentProviders) class ContentProviders(dict): def __init__(self, names=None): super().__init__() if names is not None: for position, name in enumerate(names): self[name] = lookup_ def __setitem__(self, key, value): factory = ContentProviderFactory(factory=value, name=key) super().__setitem__(key, factory) class ContentProviderFactory: def __init__(self, factory, name): self.factory = factory self.name = name self.position = getattr(factory, 'position', None) def __call__(self, manager): if self.factory != lookup_: contentProvider = self.factory( manager.content, manager.request, manager.form) else: contentProvider = zope.component.getMultiAdapter( (manager.content, manager.request, manager.form), IContentProvider, self.name) return contentProvider @zope.interface.implementer_only(interfaces.IWidgets) class FieldWidgetsAndProviders(FieldWidgets): zope.component.adapts( interfaces.IFieldsAndContentProvidersForm, interfaces.IFormLayer, zope.interface.Interface) def update(self): super().update() uniqueOrderedKeys = list(self.keys()) d = {} d.update(self) for name in self.form.contentProviders: factory = self.form.contentProviders[name] if factory.position is None: raise ValueError( "Position of the following" " content provider should be an integer: '%s'." % name) contentProvider = factory(self) shortName = name contentProvider.update() uniqueOrderedKeys.insert(factory.position, shortName) d[shortName] = contentProvider zope.location.locate(contentProvider, self, shortName) self.create_according_to_list(d, uniqueOrderedKeys) def extract(self): """See interfaces.IWidgets""" data = {} errors = () for name, widget in self.items(): if IContentProvider.providedBy(widget): continue if widget.mode == interfaces.DISPLAY_MODE: continue value = widget.field.missing_value try: widget.setErrors = self.setErrors raw = widget.extract() if raw is not interfaces.NO_VALUE: value = interfaces.IDataConverter(widget).toFieldValue(raw) zope.component.getMultiAdapter( (self.content, self.request, self.form, getattr(widget, 'field', None), widget), interfaces.IValidator).validate(value) except (zope.interface.Invalid, ValueError, MultipleErrors) as error: view = zope.component.getMultiAdapter( (error, self.request, widget, widget.field, self.form, self.content), interfaces.IErrorViewSnippet) view.update() if self.setErrors: widget.error = view errors += (view,) else: name = widget.__name__ data[name] = value for error in self.validate(data): view = zope.component.getMultiAdapter( (error, self.request, None, None, self.form, self.content), interfaces.IErrorViewSnippet) view.update() errors += (view,) if self.setErrors: self.errors = errors return data, errors
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/contentprovider.py
contentprovider.py
======================== Attribute Value Adapters ======================== In advanced, highly customized projects it is often the case that a property wants to be overridden for a particular customer in a particular case. A prime example is the label of a widget. Until this implementation of a form framework was written, widgets only could get their label from the field they were representing. Thus, wanting to change the label of a widget meant implementing a custom schema and re-registering the form in question for the custom schema. It is needless to say that this was very annoying. For this form framework, we are providing multiple levels of customization. The user has the choice to change the value of an attribute through attribute assignment or adapter lookup. The chronological order of an attribute value assignment is as follows: 1. During initialization or right thereafter, the attribute value can be set by direct attribute assignment, i.e. ``obj.attr = value`` 2. While updating the object, an adapter is looked up for the attribute. If an adapter is found, the attribute value will be overridden. Of course, if the object does not have an ``update()`` method, one can choose another location to do the adapter lookup. 3. After updating, the developer again has the choice to override the attribute allowing granularity above and beyond the adapter. The purpose of this module is to implement the availability of an attribute value using an adapter. >>> from z3c.form import value The module provides helper functions and classes, to create those adapters with as little code as possible. Static Value Adapter -------------------- To demonstrate the static value adapter, let's go back to our widget label example. Let's create a couple of simple widgets and forms first: >>> class TextWidget(object): ... label = u'Text' >>> tw = TextWidget() >>> class CheckboxWidget(object): ... label = u'Checkbox' >>> cbw = CheckboxWidget() >>> class Form1(object): ... pass >>> form1 = Form1() >>> class Form2(object): ... pass >>> form2 = Form2() We can now create a generic widget property adapter: >>> WidgetAttribute = value.StaticValueCreator( ... discriminators = ('widget', 'view') ... ) Creating the widget attribute object, using the helper function above, allows us to define the discriminators (or the granulatrity) that can be used to control a widget attribute by an adapter. In our case this is the widget itself and the form/view in which the widget is displayed. In other words, it will be possible to register a widget attribute value specifically for a particular widget, a particular form, or a combination thereof. Let's now create a label attribute adapter for the text widget, since our customer does not like the default label: >>> TextLabel = WidgetAttribute(u'My Text', widget=TextWidget) The first argument of any static attribute value is the value itself, in our case the string "My Text". The following keyword arguments are the discriminators specified in the property factory. Since we only specify the widget, the label will be available to all widgets. But first we have to register the adapter: >>> import zope.component >>> zope.component.provideAdapter(TextLabel, name='label') The name of the adapter is the attribute name of the widget. Let's now see how we can get the label: >>> from z3c.form import interfaces >>> staticValue = zope.component.getMultiAdapter( ... (tw, form1), interfaces.IValue, name='label') >>> staticValue <StaticValue u'My Text'> The resulting value object has one public method ``get()``, which returns the actual value: >>> staticValue.get() u'My Text' As we said before, the value should be available to all forms, ... >>> zope.component.getMultiAdapter( ... (tw, form2), interfaces.IValue, name='label') <StaticValue u'My Text'> ... but only to the ``TextWidget``: >>> zope.component.getMultiAdapter( ... (cbw, form2), interfaces.IValue, name='label') Traceback (most recent call last): ... ComponentLookupError: ((<CheckboxWidget...>, <Form2...>), <InterfaceClass ...IValue>, 'label') By the way, the attribute adapter factory notices, if you specify a discriminator that was not specified: >>> WidgetAttribute(u'My Text', form=Form2) Traceback (most recent call last): ... ValueError: One or more keyword arguments did not match the discriminators. >>> WidgetAttribute.discriminators ('widget', 'view') Computed Value Adapter ---------------------- A second implementation of the value adapter in the evaluated value, where one can specify a function that computes the value to be returned. The only argument to the function is the value adapter instance itself, which then contains all the discriminators as specified when creating the generic widget attribute factory. Let's take the same use case as before, but generating the value as follows: >>> def getLabelValue(adapter): ... return adapter.widget.label + ' (1)' Now we create the value adapter for it: >>> WidgetAttribute = value.ComputedValueCreator( ... discriminators = ('widget', 'view') ... ) >>> TextLabel = WidgetAttribute(getLabelValue, widget=TextWidget) After registering the adapter, ... >>> zope.component.provideAdapter(TextLabel, name='label') we now get the answers: >>> from z3c.form import interfaces >>> zope.component.getMultiAdapter( ... (tw, form1), interfaces.IValue, name='label') <ComputedValue u'Text (1)'> __Note__: The two implementations of the attribute value adapters are not meant to be canonical features that must always be used. The API is kept simple to allow you to quickly implement your own value adapter. Automatic Interface Assignment ------------------------------ Oftentimes it is desirable to register an attribute value adapter for an instance. A good example is a field, so let's create a small schema: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... firstName = zope.schema.TextLine(title=u'First Name') ... lastName = zope.schema.TextLine(title=u'Last Name') The customer now requires that the title -- which is the basis of the widget label for field widgets -- of the last name should be "Surname". Until now the option was to write a new schema changing the title. With this attribute value module, as introduced thus far, we would need to provide a special interface for the last name field, since registering a label adapter for all text fields would also change the first name. Before demonstrating the solution to this problem, let's first create a field attribute value: >>> FieldAttribute = value.StaticValueCreator( ... discriminators = ('field',) ... ) We can now create the last name title, changing only the title of the ``lastName`` field. Instead of passing in an interface of class as the field discriminator, we pass in the field instance: >>> LastNameTitle = FieldAttribute(u'Surname', field=IPerson['lastName']) The attribute value factory will automatically detect instances, create an interface on the fly, directly provide it on the field and makes it the discriminator interface for the adapter registratioon. So after registering the adapter, ... >>> zope.component.provideAdapter(LastNameTitle, name='title') the adapter is only available to the last name field and not the first name: >>> zope.component.queryMultiAdapter( ... (IPerson['lastName'],), interfaces.IValue, name='title') <StaticValue u'Surname'> >>> zope.component.queryMultiAdapter( ... (IPerson['firstName'],), interfaces.IValue, name='title')
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/value.rst
value.rst
import zope.browser.interfaces import zope.component import zope.interface import zope.schema from zope.schema import vocabulary from z3c.form import interfaces from z3c.form import util from z3c.form.i18n import MessageFactory as _ @zope.interface.implementer(interfaces.ITerms) class Terms: """Base implementation for custom ITerms.""" def getTerm(self, value): return self.terms.getTerm(value) def getTermByToken(self, token): return self.terms.getTermByToken(token) def getValue(self, token): return self.getTermByToken(token).value def __iter__(self): return iter(self.terms) def __len__(self): return self.terms.__len__() def __contains__(self, value): return self.terms.__contains__(value) @zope.interface.implementer(interfaces.ITerms) class SourceTerms(Terms): """Base implementation for ITerms using source instead of vocabulary.""" def __init__(self, context, request, form, field, source, widget): self.context = context self.request = request self.form = form self.field = field self.widget = widget self.source = source self.terms = zope.component.getMultiAdapter( (self.source, self.request), zope.browser.interfaces.ITerms) def getTerm(self, value): try: return super().getTerm(value) except KeyError: raise LookupError(value) def getTermByToken(self, token): # This is rather expensive for value in self.source: term = self.getTerm(value) if term.token == token: return term raise LookupError(token) def getValue(self, token): try: return self.terms.getValue(token) except KeyError: raise LookupError(token) def __iter__(self): for value in self.source: yield self.terms.getTerm(value) def __len__(self): return len(self.source) def __contains__(self, value): return value in self.source @zope.interface.implementer(interfaces.ITerms) @zope.component.adapter( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.IChoice, interfaces.IWidget) def ChoiceTerms(context, request, form, field, widget): if field.context is None: field = field.bind(context) terms = field.vocabulary return zope.component.queryMultiAdapter( (context, request, form, field, terms, widget), interfaces.ITerms) @zope.interface.implementer(interfaces.ITerms) class ChoiceTermsVocabulary(Terms): """ITerms adapter for zope.schema.IChoice based implementations using vocabulary.""" zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.IChoice, zope.schema.interfaces.IBaseVocabulary, interfaces.IWidget) def __init__(self, context, request, form, field, vocabulary, widget): self.context = context self.request = request self.form = form self.field = field self.widget = widget self.terms = vocabulary class MissingTermsBase: """Base class for MissingTermsMixin classes.""" def _canQueryCurrentValue(self): return (interfaces.IContextAware.providedBy(self.widget) and not self.widget.ignoreContext) def _queryCurrentValue(self): return zope.component.getMultiAdapter( (self.widget.context, self.field), interfaces.IDataManager).query() def _makeToken(self, value): """create a unique valid ASCII token""" return util.createCSSId(util.toUnicode(value)) def _makeMissingTerm(self, value): """Return a term that should be displayed for the missing token""" uvalue = util.toUnicode(value) return vocabulary.SimpleTerm( value, self._makeToken(value), title=_('Missing: ${value}', mapping=dict(value=uvalue))) class MissingTermsMixin(MissingTermsBase): """This can be used in case previous values/tokens get missing from the vocabulary and you still need to display/keep the values""" def getTerm(self, value): try: return super().getTerm(value) except LookupError: if self._canQueryCurrentValue(): curValue = self._queryCurrentValue() if curValue == value: return self._makeMissingTerm(value) raise def getTermByToken(self, token): try: return super().getTermByToken(token) except LookupError: if self._canQueryCurrentValue(): value = self._queryCurrentValue() term = self._makeMissingTerm(value) if term.token == token: # check if the given token matches the value, if not # fall back on LookupError, otherwise we might accept # any crap coming from the request return term raise LookupError(token) class MissingChoiceTermsVocabulary(MissingTermsMixin, ChoiceTermsVocabulary): """ITerms adapter for zope.schema.IChoice based implementations using vocabulary with missing terms support""" @zope.interface.implementer(interfaces.ITerms) class ChoiceTermsSource(SourceTerms): """ITerms adapter for zope.schema.IChoice based implementations using source.""" zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.IChoice, zope.schema.interfaces.IIterableSource, interfaces.IWidget) class MissingChoiceTermsSource(MissingTermsMixin, ChoiceTermsSource): """ITerms adapter for zope.schema.IChoice based implementations using source with missing terms support.""" @zope.interface.implementer_only(interfaces.IBoolTerms) class BoolTerms(Terms): """Default yes and no terms are used by default for IBool fields.""" zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.IBool, interfaces.IWidget) trueLabel = _('yes') falseLabel = _('no') def __init__(self, context, request, form, field, widget): self.context = context self.request = request self.form = form self.field = field self.widget = widget terms = [vocabulary.SimpleTerm(*args) for args in [(True, 'true', self.trueLabel), (False, 'false', self.falseLabel)]] self.terms = vocabulary.SimpleVocabulary(terms) @zope.interface.implementer(interfaces.ITerms) @zope.component.adapter( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.ICollection, interfaces.IWidget) def CollectionTerms(context, request, form, field, widget): terms = field.value_type.bind(context).vocabulary return zope.component.queryMultiAdapter( (context, request, form, field, terms, widget), interfaces.ITerms) class CollectionTermsVocabulary(Terms): """ITerms adapter for zope.schema.ICollection based implementations using vocabulary.""" zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.ICollection, zope.schema.interfaces.IBaseVocabulary, interfaces.IWidget) def __init__(self, context, request, form, field, vocabulary, widget): self.context = context self.request = request self.form = form self.field = field self.widget = widget self.terms = vocabulary class MissingCollectionTermsMixin(MissingTermsBase): """`MissingTermsMixin` adapted to collections.""" def getTerm(self, value): try: return super().getTerm(value) except LookupError: if self._canQueryCurrentValue(): if value in self._queryCurrentValue(): return self._makeMissingTerm(value) raise def getTermByToken(self, token): try: return super().getTermByToken(token) except LookupError: if self._canQueryCurrentValue(): for value in self._queryCurrentValue(): term = self._makeMissingTerm(value) if term.token == token: # check if the given token matches the value, if not # fall back on LookupError, otherwise we might accept # any crap coming from the request return term raise def getValue(self, token): try: return super().getValue(token) except LookupError: if self._canQueryCurrentValue(): for value in self._queryCurrentValue(): term = self._makeMissingTerm(value) if term.token == token: # check if the given token matches the value, if not # fall back on LookupError, otherwise we might accept # any crap coming from the request return value raise class MissingCollectionTermsVocabulary(MissingCollectionTermsMixin, CollectionTermsVocabulary): """ITerms adapter for zope.schema.ICollection based implementations using vocabulary with missing terms support.""" @zope.interface.implementer(interfaces.ITerms) class CollectionTermsSource(SourceTerms): """ITerms adapter for zope.schema.ICollection based implementations using source.""" zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.ICollection, zope.schema.interfaces.IIterableSource, interfaces.IWidget) class MissingCollectionTermsSource(MissingCollectionTermsMixin, CollectionTermsSource): """ITerms adapter for zope.schema.ICollection based implementations using source with missing terms support."""
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/term.py
term.py
================= Content Providers ================= We want to mix fields and content providers. This allow to enrich the form by interlacing html snippets produced by content providers. For instance, we might want to render the table of results in a search form. We might also need to render HTML close to a widget as a handle used when improving UI with Ajax. Adding HTML outside the widgets avoids the systematic need of subclassing or changing the full widget rendering. Test setup ---------- Before we can use a widget manager, the ``IFieldWidget`` adapter has to be registered for the ``ITextLine`` field:: >>> import zope.component >>> import zope.interface >>> from z3c.form import interfaces, widget >>> from z3c.form.browser import text >>> from z3c.form.testing import TestRequest >>> @zope.component.adapter(zope.schema.TextLine, TestRequest) ... @zope.interface.implementer(interfaces.IFieldWidget) ... def TextFieldWidget(field, request): ... return widget.FieldWidget(field, text.TextWidget(request)) >>> zope.component.provideAdapter(TextFieldWidget) >>> from z3c.form import converter >>> zope.component.provideAdapter(converter.FieldDataConverter) >>> zope.component.provideAdapter(converter.FieldWidgetDataConverter) We define a simple test schema with fields:: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... ... id = zope.schema.TextLine( ... title=u'ID', ... description=u"The person's ID.", ... required=True) ... ... fullname = zope.schema.TextLine( ... title=u'FullName', ... description=u"The person's name.", ... required=True) ... A class that implements the schema:: >>> class Person(object): ... id = 'james' ... fullname = 'James Bond' The usual request instance:: >>> request = TestRequest() We want to insert a content provider in between fields. We define a test content provider that renders extra help text:: >>> from zope.publisher.browser import BrowserView >>> from zope.contentprovider.interfaces import IContentProvider >>> class ExtendedHelp(BrowserView): ... def __init__(self, context, request, view): ... super(ExtendedHelp, self).__init__(context, request) ... self.__parent__ = view ... ... def update(self): ... self.person = self.context.id ... ... def render(self): ... return '<div class="ex-help">Help about person %s</div>' % self.person Form definition --------------- The meat of the tests begins here. We define a form as usual by inheriting from ``form.Form``:: >>> from z3c.form import field, form >>> from zope.interface import implementer To enable content providers, the form class must : 1. implement ``IFieldsAndContentProvidersForm`` 2. have a ``contentProviders`` attribute that is an instance of the ``ContentProviders`` class. :: >>> from z3c.form.interfaces import IFieldsAndContentProvidersForm >>> from z3c.form.contentprovider import ContentProviders Content provider assignment ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Content providers classes (factories) can be assigned directly to the ``ContentProviders`` container:: >>> @implementer(IFieldsAndContentProvidersForm) ... class PersonForm(form.Form): ... fields = field.Fields(IPerson) ... ignoreContext = True ... contentProviders = ContentProviders() ... contentProviders['longHelp'] = ExtendedHelp ... contentProviders['longHelp'].position = 1 Let's instantiate content and form instances:: >>> person = Person() >>> personForm = PersonForm(person, request) Once the widget manager has been updated, it holds the content provider:: >>> from z3c.form.contentprovider import FieldWidgetsAndProviders >>> manager = FieldWidgetsAndProviders(personForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> widgets = manager >>> ids = sorted(widgets.keys()) >>> ids ['fullname', 'id', 'longHelp'] >>> widgets['longHelp'] <ExtendedHelp object at ...> >>> widgets['id'] <TextWidget 'form.widgets.id'> >>> widgets['fullname'] <TextWidget 'form.widgets.fullname'> >>> manager.get('longHelp').render() '<div class="ex-help">Help about person james</div>' Content provider lookup ~~~~~~~~~~~~~~~~~~~~~~~ Forms can also refer by name to content providers. Let's register a content provider by name as usual:: >>> from zope.component import provideAdapter >>> from zope.contentprovider.interfaces import IContentProvider >>> from z3c.form.interfaces import IFormLayer >>> provideAdapter(ExtendedHelp, ... (zope.interface.Interface, ... IFormLayer, ... zope.interface.Interface), ... provides=IContentProvider, name='longHelp') Let the form refer to it:: >>> @implementer(IFieldsAndContentProvidersForm) ... class LookupPersonForm(form.Form): ... prefix = 'form.' ... fields = field.Fields(IPerson) ... ignoreContext = True ... contentProviders = ContentProviders(['longHelp']) ... contentProviders['longHelp'].position = 2 >>> lookupForm = LookupPersonForm(person, request) After update, the widget manager refers to the content provider:: >>> from z3c.form.contentprovider import FieldWidgetsAndProviders >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> widgets = manager >>> ids = sorted(widgets.keys()) >>> ids ['fullname', 'id', 'longHelp'] >>> widgets['longHelp'] <ExtendedHelp object at ...> >>> widgets['id'] <TextWidget 'form.widgets.id'> >>> widgets['fullname'] <TextWidget 'form.widgets.fullname'> >>> manager.get('longHelp').render() '<div class="ex-help">Help about person james</div>' Providers position ~~~~~~~~~~~~~~~~~~ Until here, we have defined position for content providers without explaining how it is used. A position needs to be defined for each provider. Let's forget to define a position:: >>> @implementer(IFieldsAndContentProvidersForm) ... class UndefinedPositionForm(form.Form): ... prefix = 'form.' ... fields = field.Fields(IPerson) ... ignoreContext = True ... contentProviders = ContentProviders(['longHelp']) >>> form = UndefinedPositionForm(person, request) >>> manager = FieldWidgetsAndProviders(form, request, person) >>> manager.ignoreContext = True When updating the widget manager, we get an exception:: >>> manager.update() Traceback (most recent call last): ... ValueError: Position of the following content provider should be an integer: 'longHelp'. Let's check positioning of content providers:: >>> LookupPersonForm.contentProviders['longHelp'].position = 0 >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> list(manager.values()) [<ExtendedHelp object at ...>, <TextWidget 'form.widgets.id'>, <TextWidget 'form.widgets.fullname'>] >>> LookupPersonForm.contentProviders['longHelp'].position = 1 >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> list(manager.values()) [<TextWidget 'form.widgets.id'>, <ExtendedHelp object at ...>, <TextWidget 'form.widgets.fullname'>] >>> LookupPersonForm.contentProviders['longHelp'].position = 2 >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> list(manager.values()) [<TextWidget 'form.widgets.id'>, <TextWidget 'form.widgets.fullname'>, <ExtendedHelp object at ...>] Using value larger than sequence length implies end of sequence:: >>> LookupPersonForm.contentProviders['longHelp'].position = 3 >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> list(manager.values()) [<TextWidget 'form.widgets.id'>, <TextWidget 'form.widgets.fullname'>, <ExtendedHelp object at ...>] A negative value is interpreted same as ``insert`` method of Python lists:: >>> LookupPersonForm.contentProviders['longHelp'].position = -1 >>> manager = FieldWidgetsAndProviders(lookupForm, request, person) >>> manager.ignoreContext = True >>> manager.update() >>> list(manager.values()) [<TextWidget 'form.widgets.id'>, <ExtendedHelp object at ...>, <TextWidget 'form.widgets.fullname'>] Rendering the form ------------------ Once the form has been updated, it can be rendered. Since we have not assigned a template yet, we have to do it now. We have a small template as part of this example:: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate >>> from z3c.form import tests >>> def personTemplate(form): ... form.template = BoundPageTemplate( ... ViewPageTemplateFile( ... 'simple_edit_with_providers.pt', ... os.path.dirname(tests.__file__)), form) >>> personTemplate(personForm) To enable form updating, all widget adapters must be registered:: >>> from z3c.form.testing import setupFormDefaults >>> setupFormDefaults() ``FieldWidgetsAndProviders`` is registered as widget manager for ``IFieldsAndContentProvidersForm``:: >>> personForm.update() >>> personForm.widgets FieldWidgetsAndProviders([...]) Let's render the form:: >>> print(personForm.render()) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-id">ID</label> <input id="form-widgets-id" name="form.widgets.id" class="text-widget required textline-field" value="" type="text" /> </div> <div class="row"> <div class="ex-help">Help about person james</div> </div> <div class="row"> <label for="form-widgets-fullname">FullName</label> <input id="form-widgets-fullname" name="form.widgets.fullname" class="text-widget required textline-field" value="" type="text" /> </div> </form> </body> </html>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/contentprovider.rst
contentprovider.rst
=========== Error Views =========== Error views are looked up every time a validation error occurs during data extraction and/or validation. Unfortunately, it was often hard to adjust error messages based on specific situations. The error view implementation in this package is designed to provide several high-level features that make customizing error messages easier. >>> from z3c.form import error Creating and Displaying the Default Error View ---------------------------------------------- Let's create an error view message for the ``TooSmall`` validation error: >>> from zope.schema.interfaces import TooSmall, TooBig >>> from z3c.form.testing import TestRequest >>> view = error.ErrorViewSnippet( ... TooSmall(), TestRequest(), None, None, None, None) >>> view <ErrorViewSnippet for TooSmall> The discriminators for an error view are as follows: error, request, widget, field, form, and content. After updating the view, a test message is available: >>> view.update() >>> view.message 'Value is too small' And after registering a template for the error view, we can also render the view: >>> import os >>> filename = os.path.join(os.path.dirname(error.__file__), 'error.pt') >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form import interfaces >>> zope.component.provideAdapter( ... error.ErrorViewTemplateFactory(filename, 'text/html'), ... (interfaces.IErrorViewSnippet, None), IPageTemplate) >>> print(view.render()) <div class="error">Value is too small</div> Customizing Error Messages -------------------------- As you can imagine, writing new error views for every scenario can be very tedious, especially if you only want to provide a specific error *message*. So let's create somewhat more interesting setup: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... name = zope.schema.TextLine(title='Name') ... age = zope.schema.Int( ... title='Age', ... min=0) You must agree, that the follwoing message is pretty dull when entering a negative age: >>> print(view.render()) <div class="error">Value is too small</div> So let's register a better message for this particular situation: >>> NegativeAgeMessage = error.ErrorViewMessage( ... 'A negative age is not sensible.', ... error=TooSmall, field=IPerson['age']) >>> zope.component.provideAdapter(NegativeAgeMessage, name='message') The created object is a common attribute value for the error view message. The discriminators are the same as for the error view itself. Now we create an error view message for ``TooSmall`` of the age field: >>> view = error.ErrorViewSnippet( ... TooSmall(), TestRequest(), None, IPerson['age'], None, None) >>> view.update() >>> print(view.render()) <div class="error">A negative age is not sensible.</div> Much better, isn't it? We can also provide dynamic error view messages that are computed each time we get an error. For example, we have an IAdult interface that have minimal age of 18: >>> class IAdult(zope.interface.Interface): ... age = zope.schema.Int(title='Age', min=18) Now, let's create a function that will be called by a message value adapter, it receives one argument, a special ``z3c.form.value.ComputedValue`` object that will have all needed attributes: error, request, widget, field, form and content. Let's use one of them: >>> def getAgeTooSmallErrorMessage(value): ... return 'Given age is smaller than %d, you are not adult.' % ( ... value.field.min) Now, register the computed view message: >>> ComputedAgeMessage = error.ComputedErrorViewMessage( ... getAgeTooSmallErrorMessage, error=TooSmall, field=IAdult['age']) >>> zope.component.provideAdapter(ComputedAgeMessage, name='message') Now, the error view snippet will show dynamically generated message: >>> view = error.ErrorViewSnippet( ... TooSmall(), TestRequest(), None, IAdult['age'], None, None) >>> view.update() >>> print(view.render()) <div class="error">Given age is smaller than 18, you are not adult.</div> Registering Custom Error Views ------------------------------ Even though message attribute values will solve most of our customization needs, sometimes one wishes to register a custom view to have more complex views. In this example we wish to register a custom error message: >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import tests >>> class NegativeAgeView(error.ErrorViewSnippet): ... template = ViewPageTemplateFile( ... 'custom_error.pt', os.path.dirname(tests.__file__)) We now need to assert the special discriminators specific to this view: >>> error.ErrorViewDiscriminators( ... NegativeAgeView, error=TooSmall, field=IPerson['age']) After registering the new and default error view, ... >>> zope.component.provideAdapter(NegativeAgeView) >>> zope.component.provideAdapter(error.ErrorViewSnippet) we can now make use of it, but only for this particular field and error: >>> zope.component.getMultiAdapter( ... (TooSmall(), TestRequest(), None, IPerson['age'], None, None), ... interfaces.IErrorViewSnippet) <NegativeAgeView for TooSmall> Other combinations will return the default screen instead: >>> zope.component.getMultiAdapter( ... (TooBig(), TestRequest(), None, IPerson['age'], None, None), ... interfaces.IErrorViewSnippet) <ErrorViewSnippet for TooBig> >>> zope.component.getMultiAdapter( ... (TooSmall(), TestRequest(), None, IPerson['name'], None, None), ... interfaces.IErrorViewSnippet) <ErrorViewSnippet for TooSmall> Value Error View Snippets ------------------------- In the previous examples we have always worked with the view of the validation error. Since data managers can also return value errors, there is also an error view for them: >>> valueError = ValueError(2) >>> errorView = error.ValueErrorViewSnippet( ... valueError, TestRequest(), None, None, None, None) It uses the same template: >>> errorView.update() >>> print(errorView.render()) <div class="error">The system could not process the given value.</div> Unfortunately, we cannot make use of the original string representation of the value error, since it cannot be localized well enough. Thus we provide our own message. Of course, the message can be overridden: >>> CustomMessage = error.ErrorViewMessage( ... 'The entered value is not valid.', error=ValueError) >>> zope.component.provideAdapter(CustomMessage, name='message') Let's now render the snippet again: >>> errorView.update() >>> print(errorView.render()) <div class="error">The entered value is not valid.</div> Invalid Error View Snippets --------------------------- When invariants are used, commonly the ``Invalid`` exception (from the ``zope.interface`` package) is raised from within the invariant, if the invariant finds a problem. We need a special error view snippet for this class of errors: >>> invalidError = zope.interface.Invalid('The data was invalid.') >>> errorView = error.InvalidErrorViewSnippet( ... invalidError, TestRequest(), None, None, None, None) Since the same template as before is used, the error simply renders: >>> errorView.update() >>> print(errorView.render()) <div class="error">The data was invalid.</div> As you can see, the first argument to the exception is used as the explanatory message of the error.
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/error.rst
error.rst
======= Widgets ======= Widgets are small UI components that accept and process the textual user input. The only responsibility of a widget is to represent a value to the user, allow it to be modified and then return a new value. Good examples of widgets include the Qt widgets and HTML widgets. The widget is not responsible for converting its value to the desired internal value or validate the incoming data. These responsibilities are passed data converters and validators, respectively. There are several problems that can be identified in the original Zope 3 widget implementation located at ``zope.app.form``. (1) Field Dependence -- Widgets are always views of fields. While this might be a correct choice for a high-level API, it is fundamentally wrong. It disallows us to use widgets without defining fields. This also couples certain pieces of information too tightly to the field, especially, value retrieval from and storage to the context, validation and raw data conversion. (2) Form Dependence -- While widgets do not have to be located within a form, they are usually tightly coupled to it. It is very difficult to use widgets outside the context of a form. (3) Traversability -- Widgets cannot be traversed, which means that they cannot interact easily using Javascript. This is not a fundamental problem, but simply a lack of the current design to recognize that small UI components must also be traversable and thus have a URI. (4) Customizability -- A consequence of issue (1) is that widgets are not customizable enough. Implementing real-world projects has shown that widgets often want a very fine-grained ability to customize values. A prime example is the label. Because the label of a widget is retrieved from the field title, it is impossible to provide an alternative label for a widget. While the label could be changed from the form, this would require rewriting the entire form to change a label. Instead, we often endde up writing cusom schemas. (5) Flexibility -- Oftentimes it is desired to have one widget, but multiple styles of representation. For example, in one scenario the widget uses a plain HTML widget and in another a fancy JavaScript widget is used. The current implementation makes it very hard to provide alternative styles for a widget. Creating and Using Simple Widgets --------------------------------- When using the widget API by itself, the simplest way to use it is to just instantiate it using the request: >>> from z3c.form.testing import TestRequest >>> from z3c.form import widget >>> request = TestRequest() >>> age = widget.Widget(request) In this case we instantiated a generic widget. A full set of simple browser-based widgets can be found in the ``browser/`` package. Since no helper components are around to fill the attributes of the widget, we have to do it by hand: >>> age.name = 'age' >>> age.label = 'Age' >>> age.value = '39' The most important attributes are the "name" and the "value". The name is used to identify the widget within the form. The value is either the value to be manipulated or the default value. The value must be provided in the form the widget needs it. It is the responsibility of a data converter to convert between the widget value and the desired internal value. Before we can render the widget, we have to register a template for the widget. The first step is to define the template: >>> import tempfile >>> textWidgetTemplate = tempfile.mktemp('text.pt') >>> with open(textWidgetTemplate, 'w') as file: ... _ = file.write(''' ... <html xmlns="http://www.w3.org/1999/xhtml" ... xmlns:tal="http://xml.zope.org/namespaces/tal" ... tal:omit-tag=""> ... <input type="text" name="" value="" ... tal:attributes="name view/name; value view/value;" /> ... </html> ... ''') Next, we have to create a template factory for the widget: >>> from z3c.form.widget import WidgetTemplateFactory >>> factory = WidgetTemplateFactory( ... textWidgetTemplate, widget=widget.Widget) The first argument, which is also required, is the path to the template file. An optional ``content_type`` keyword argument allows the developer to specify the output content type, usually "text/html". Then there are five keyword arguments that specify the discriminators of the template: * ``context`` -- This is the context in which the widget is displayed. In a simple widget like the one we have now, the context is ``None``. * ``request`` -- This discriminator allows you to specify the type of request for which the widget will be available. In our case this would be a browser request. Note that browser requests can be further broken into layer, so you could also specify a layer interface here. * ``view`` -- This is the view from which the widget is used. The simple widget at hand, does not have a view associated with it though. * ``field`` -- This is the field for which the widget provides a representation. Again, this simple widget does not use a field, so it is ``None``. * ``widget`` -- This is the widget itself. With this discriminator you can specify for which type of widget you are providing a template. We can now register the template factory. The name of the factory is the mode of the widget. By default, there are two widget modes: "input" and "display". However, since the mode is just a string, one can develop other kinds of modes as needed for a project. The default mode is "input": >>> from z3c.form import interfaces >>> age.mode is interfaces.INPUT_MODE True >>> import zope.component >>> zope.component.provideAdapter(factory, name=interfaces.INPUT_MODE) Once everything is set up, the widget is updated and then rendered: >>> age.update() >>> print(age.render()) <input type="text" name="age" value="39" /> If a value is found in the request, it takes precedence, since the user entered the value: >>> age.request = TestRequest(form={'age': '25'}) >>> age.update() >>> print(age.render()) <input type="text" name="age" value="25" /> However, there is an option to turn off all request data: >>> age.value = '39' >>> age.ignoreRequest = True >>> age.update() >>> print(age.render()) <input type="text" name="age" value="39" /> Additionally the widget provides a dictionary representation of its data through a json_data() method: >>> from pprint import pprint >>> pprint(age.json_data()) {'error': '', 'id': '', 'label': 'Age', 'mode': 'input', 'name': 'age', 'required': False, 'type': 'text', 'value': '39'} Creating and Using Field Widgets -------------------------------- An extended form of the widget allows fields to control several of the widget's properties. Let's create a field first: >>> ageField = zope.schema.Int( ... __name__ = 'age', ... title = 'Age', ... min = 0, ... max = 130) We can now use our simple widget and create a field widget from it: >>> ageWidget = widget.FieldWidget(ageField, age) Such a widget provides ``IFieldWidget``: >>> interfaces.IFieldWidget.providedBy(ageWidget) True Of course, this is more commonly done using an adapter. Commonly those adapters look like this: >>> @zope.component.adapter(zope.schema.Int, TestRequest) ... @zope.interface.implementer(interfaces.IFieldWidget) ... def IntWidget(field, request): ... return widget.FieldWidget(field, widget.Widget(request)) >>> zope.component.provideAdapter(IntWidget) >>> ageWidget = zope.component.getMultiAdapter((ageField, request), ... interfaces.IFieldWidget) Now we just have to update and render the widget: >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" /> There is no initial value for the widget, since there is no value in the request and the field does not provide a default. Let's now give our field a default value and see what happens: >>> ageField.default = 30 >>> ageWidget.update() Traceback (most recent call last): ... TypeError: ('Could not adapt', <Widget 'age'>, <InterfaceClass z3c.form.interfaces.IDataConverter>) In order for the widget to be able to take the field's default value and use it to provide an initial value the widget, we need to provide a data converter that defines how to convert from the field value to the widget value. >>> from z3c.form import converter >>> zope.component.provideAdapter(converter.FieldWidgetDataConverter) >>> zope.component.provideAdapter(converter.FieldDataConverter) >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="30" /> Again, the request value is honored above everything else: >>> ageWidget.request = TestRequest(form={'age': '25'}) >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="25" /> Creating and Using Context Widgets ---------------------------------- When widgets represent an attribute value of an object, then this object must be set as the context of the widget: >>> class Person(object): ... age = 45 >>> person = Person() >>> ageWidget.context = person >>> zope.interface.alsoProvides(ageWidget, interfaces.IContextAware) The result is that the context value takes over precendence over the default value: >>> ageWidget.request = TestRequest() >>> ageWidget.update() Traceback (most recent call last): ... ComponentLookupError: ((...), <InterfaceClass ...IDataManager>, '') This call fails because the widget does not know how to extract the value from the context. Registering a data manager for the widget does the trick: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.AttributeField) >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="45" /> If the context value is unknown (None), the default value kicks in. >>> person.age = None >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="30" /> Unless the widget is explicitely asked to not to show defaults. This is handy for EditForms. >>> ageWidget.showDefault = False >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="" /> >>> ageWidget.showDefault = True >>> person.age = 45 The context can be explicitely ignored, making the widget display the default value again: >>> ageWidget.ignoreContext = True >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="30" /> Again, the request value is honored above everything else: >>> ageWidget.request = TestRequest(form={'age': '25'}) >>> ageWidget.ignoreContext = False >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="25" /> But what happens if the object we are working on is security proxied? In particular, what happens, if the access to the attribute is denied. To see what happens, we have to create a proxied person: >>> from zope.security import checker >>> PersonChecker = checker.Checker({'age': 'Access'}, {'age': 'Edit'}) >>> ageWidget.request = TestRequest() >>> ageWidget.context = checker.ProxyFactory(Person(), PersonChecker) After changing the security policy, ... >>> from zope.security import management >>> from z3c.form import testing >>> management.endInteraction() >>> newPolicy = testing.SimpleSecurityPolicy() >>> oldPolicy = management.setSecurityPolicy(newPolicy) >>> management.newInteraction() it is not possible anymore to update the widget: >>> ageWidget.update() Traceback (most recent call last): ... Unauthorized: (<Person object at ...>, 'age', 'Access') If no security declaration has been made at all, we get a ``ForbiddenAttribute`` error: >>> ageWidget.context = checker.ProxyFactory(Person(), checker.Checker({})) >>> ageWidget.update() Traceback (most recent call last): ... ForbiddenAttribute: ('age', <Person object at ...>) Let's clean up the setup: >>> management.endInteraction() >>> newPolicy = management.setSecurityPolicy(oldPolicy) >>> management.newInteraction() >>> ageWidget.context = Person() Dynamically Changing Attribute Values ------------------------------------- Once widgets are used within a framework, it is very tedious to write Python code to adjust certain attributes, even though hooks exist. The easiest way to change those attribute values is actually to provide an adapter that provides the custom value. We can create a custom label for the age widget: >>> AgeLabel = widget.StaticWidgetAttribute( ... 'Current Age', ... context=None, request=None, view=None, field=ageField, widget=None) Clearly, this code does not require us to touch the orginal form and widget code, given that we have enough control over the selection. In the example above, all the selection discriminators are listed for demonstration purposes. Of course, the label in this case can be created as follows: >>> AgeLabel = widget.StaticWidgetAttribute('Current Age', field=ageField) Much better, isn't it? Initially the label is the title of the field: >>> ageWidget.label 'Age' Let's now simply register the label as a named adapter; the name is the name of the attribute to change: >>> zope.component.provideAdapter(AgeLabel, name='label') Asking the widget for the label now will return the newly registered label: >>> ageWidget.update() >>> ageWidget.label 'Current Age' Of course, simply setting the label or changing the label extraction via a sub-class are other options you might want to consider. Furthermore, you could also create a computed attribute value or implement your own component. Overriding other attributes, such as ``required``, is done in the same way. If any widget provides new attributes, they are also overridable this way. For example, the selection widget defines a label for the option that no value was selected. We often want to override this, because the German translation sucks or the wording is often too generic. Widget implementation should add names of overridable attributes to their "_adapterValueAttributes" internal attribute. Let's try to override the ``required`` attribute. By default the widget is required, because the field is required as well: >>> ageWidget.required True Let's provide a static widget attribute adapter with name "required": >>> AgeNotRequired = widget.StaticWidgetAttribute(False, field=ageField) >>> zope.component.provideAdapter(AgeNotRequired, name="required") Now, let's check if it works: >>> ageWidget.update() >>> ageWidget.required False Overriding the default value is somewhat special due to the complexity of obtaining the value. So let's register one now: >>> AgeDefault = widget.StaticWidgetAttribute(50, field=ageField) >>> zope.component.provideAdapter(AgeDefault, name="default") Let's now instantiate, update and render the widget to see the default value: >>> ageWidget = zope.component.getMultiAdapter((ageField, request), ... interfaces.IFieldWidget) >>> ageWidget.update() >>> print(ageWidget.render()) <input type="text" name="age" value="50" /> This value is also respected by the json_data method: >>> from pprint import pprint >>> pprint(ageWidget.json_data()) {'error': '', 'id': 'age', 'label': 'Current Age', 'mode': 'input', 'name': 'age', 'required': False, 'type': 'text', 'value': '50'} Sequence Widget --------------- A common use case in user interfaces is to ask the user to select one or more items from a set of options/choices. The ``widget`` module provides a basic widget implementation to support this use case. The options available for selections are known as terms. Initially, there are no terms: >>> request = TestRequest() >>> seqWidget = widget.SequenceWidget(request) >>> seqWidget.name = 'seq' >>> seqWidget.terms is None True There are two ways terms can be added, either manually or via an adapter. Those term objects must provide ``ITerms``. There is no simple default implementation, so we have to provide one ourselves: >>> from zope.schema import vocabulary >>> @zope.interface.implementer(interfaces.ITerms) ... class Terms(vocabulary.SimpleVocabulary): ... def getValue(self, token): ... return self.getTermByToken(token).value >>> terms = Terms( ... [Terms.createTerm(1, 'v1', 'Value 1'), ... Terms.createTerm(2, 'v2', 'Value 2'), ... Terms.createTerm(3, 'v3', 'Value 3')]) >>> seqWidget.terms = terms Once the ``terms`` attribute is set, updating the widgets does not change the terms: >>> seqWidget.update() >>> [term.value for term in seqWidget.terms] [1, 2, 3] The value of a sequence widget is a tuple/list of term tokens. When extracting values from the request, the values must be valid tokens, otherwise the default value is returned: >>> seqWidget.request = TestRequest(form={'seq': ['v1']}) >>> seqWidget.extract() ('v1',) >>> seqWidget.request = TestRequest(form={'seq': ['v4']}) >>> seqWidget.extract() <NO_VALUE> >>> seqWidget.request = TestRequest(form={'seq-empty-marker': '1'}) >>> seqWidget.extract() () Note that we also support single values being returned outside a sequence. The extracted value is then wrapped by a tuple. This feature is useful when integrating with third-party client frameworks that do not know about the Zope naming conventions. >>> seqWidget.request = TestRequest(form={'seq': 'v1'}) >>> seqWidget.extract() ('v1',) If the no-value token has been selected, it is returned without further verification: >>> seqWidget.request = TestRequest(form={'seq': [seqWidget.noValueToken]}) >>> seqWidget.extract() ('--NOVALUE--',) Since the value of the widget is a tuple of tokens, when displaying the values, they have to be converted to the title of the term: >>> seqWidget.value = ('v1', 'v2') >>> seqWidget.displayValue ['Value 1', 'Value 2'] Unknown values/terms get silently ignored. >>> seqWidget.value = ('v3', 'v4') >>> seqWidget.displayValue ['Value 3'] When input forms are directly switched to display forms within the same request, it can happen that the value contains the "--NOVALUE--" token entry. This entry should be silently ignored: >>> seqWidget.value = (seqWidget.noValueToken,) >>> seqWidget.displayValue [] To demonstrate how the terms is automatically chosen by a widget, we should instantiate a field widget. Let's do this with a choice field: >>> seqField = zope.schema.Choice( ... title='Sequence Field', ... vocabulary=terms) Let's now create the field widget: >>> seqWidget = widget.FieldWidget(seqField, widget.SequenceWidget(request)) >>> seqWidget.terms The terms should be available as soon as the widget is updated: >>> seqWidget.update() Traceback (most recent call last): ... ComponentLookupError: ((...), <InterfaceClass ...ITerms>, '') This failed, because we did not register an adapter for the terms yet. After the adapter is registered, everything should work as expected: >>> from z3c.form import term >>> zope.component.provideAdapter(term.ChoiceTermsVocabulary) >>> zope.component.provideAdapter(term.ChoiceTerms) >>> seqWidget.update() >>> seqWidget.terms <z3c.form.term.ChoiceTermsVocabulary object at ...> The representation of this widget as json looks a bit different: >>> from pprint import pprint >>> pprint(seqWidget.json_data()) {'error': '', 'id': '', 'label': 'Sequence Field', 'mode': 'input', 'name': '', 'required': True, 'type': 'sequence', 'value': ()} So that's it. Everything else is the same from then on. Multi Widget ------------ A common use case in user interfaces is to ask the user to define one or more items. The ``widget`` module provides a basic widget implementation to support this use case. The `MultiWidget` allows to store none, one or more values for a sequence or dictionary field. Don't get confused by the term sequence. The sequence used in `SequenceWidget` means that the widget can choose from a sequence of values which is really a collection. The `MultiWidget` can collect values to build and store a sequence of values like those used in `ITuple` or `IList` field. >>> request = TestRequest() >>> multiWidget = widget.MultiWidget(request) >>> multiWidget.name = 'multi.name' >>> multiWidget.id = 'multi-id' >>> multiWidget.value [] Let's define a field for our multi widget: >>> multiField = zope.schema.List( ... value_type=zope.schema.Int(default=42)) >>> multiWidget.field = multiField If the multi is used with a schema.List the value of a multi widget is always list. When extracting values from the request, the values must be a list of valid values based on the value_type field used from the used sequence field. The widget also uses a counter which is required for processing the input from a request. The counter is a marker for build the right amount of enumerated widgets. If we provide no request we will get no value: >>> multiWidget.extract() <NO_VALUE> If we provide an empty counter we will get an empty list. This is accordance with Widget.extract(), where a missing request value is <NO_VALUE> and an empty ('') request value is ''. >>> multiWidget.request = TestRequest(form={'multi.name.count':'0'}) >>> multiWidget.extract() [] If we provide real values within the request, we will get it back: >>> multiWidget.request = TestRequest(form={'multi.name.count':'2', ... 'multi.name.0':'42', ... 'multi.name.1':'43'}) >>> multiWidget.extract() ['42', '43'] If we provide a bad value we will get the bad value within the extract method. Our widget update process will validate this bad value later: >>> multiWidget.request = TestRequest(form={'multi.name.count':'1', ... 'multi.name.0':'bad'}) >>> multiWidget.extract() ['bad'] Storing a widget value forces to update the (sub) widgets. This forces also to validate the (sub) widget values. To show this we need to register a validator: >>> from z3c.form.validator import SimpleFieldValidator >>> zope.component.provideAdapter(SimpleFieldValidator) Since the value of the widget is a list of (widget) value items, when displaying the values, they can be used as they are: >>> multiWidget.request = TestRequest(form={'multi.name.count':'2', ... 'multi.name.0':'42', ... 'multi.name.1':'43'}) >>> multiWidget.value = multiWidget.extract() >>> multiWidget.value ['42', '43'] Each widget normally gets first processed by it's update method call after initialization. This update call forces to call extract, which first will get the right amount of (sub) widgets by the given counter value. Based on that counter value the right amount of widgets will get created. Each widget will return it's own value and this collected values get returned by the extract method. The multi widget update method will then store this values if any given as multi widget value argument. If extract doesn't return a value the multi widget update method will use it's default value. If we store a given value from the extract as multi widget value, this will force to setup the multi widget widgets based on the given values and apply the right value for them. After that the multi widget is ready for rendering. The good thing about that pattern is that it is possible to set a value before or after the update method is called. At any time if we change the multi widget value the (sub) widgets get updated within the new relevant value. >>> multiRequest = TestRequest(form={'multi.name.count':'2', ... 'multi.name.0':'42', ... 'multi.name.1':'43'}) >>> multiWidget = widget.FieldWidget(multiField, widget.MultiWidget( ... multiRequest)) >>> multiWidget.name = 'multi.name' >>> multiWidget.value [] >>> multiWidget.update() >>> multiWidget.widgets[0].value '42' >>> multiWidget.widgets[1].value '43' >>> multiWidget.value ['42', '43'] MultiWidget also declares the ``allowAdding`` and ``allowRemoving`` attributes that can be used in browser presentation to control add/remove button availability. To ease working with common cases, the ``updateAllowAddRemove`` method provided that will set those attributes in respect to field's min_length and max_length, if the field provides zope.schema.interfaces.IMinMaxLen interface. Let's define a field with min and max length constraints and create a widget for it. >>> multiField = zope.schema.List( ... value_type=zope.schema.Int(), ... min_length=2, ... max_length=5) >>> request = TestRequest() >>> multiWidget = widget.FieldWidget(multiField, widget.MultiWidget(request)) Lets ensure that the minimum number of widgets are created. >>> multiWidget.update() >>> len(multiWidget.widgets) 2 Now, let's check if the function will do the right thing depending on the value: No value: >>> multiWidget.updateAllowAddRemove() >>> multiWidget.allowAdding, multiWidget.allowRemoving (True, False) Minimum length: >>> multiWidget.value = ['3', '5'] >>> multiWidget.updateAllowAddRemove() >>> multiWidget.allowAdding, multiWidget.allowRemoving (True, False) Some allowed length: >>> multiWidget.value = ['3', '5', '8', '6'] >>> multiWidget.updateAllowAddRemove() >>> multiWidget.allowAdding, multiWidget.allowRemoving (True, True) Maximum length: >>> multiWidget.value = ['3', '5', '8', '6', '42'] >>> multiWidget.updateAllowAddRemove() >>> multiWidget.allowAdding, multiWidget.allowRemoving (False, True) Over maximum length: >>> multiWidget.value = ['3', '5', '8', '6', '42', '45'] >>> multiWidget.updateAllowAddRemove() >>> multiWidget.allowAdding, multiWidget.allowRemoving (False, True) I know a guy who once switched widget mode in the middle. All simple widgets are easy to hack, but multiWidget needs to update all subwidgets: >>> [w.mode for w in multiWidget.widgets] ['input', 'input', 'input', 'input', 'input', 'input'] Switch the multiWidget mode: >>> multiWidget.mode = interfaces.DISPLAY_MODE Yes, all subwidgets switch mode: >>> [w.mode for w in multiWidget.widgets] ['display', 'display', 'display', 'display', 'display', 'display'] The json data representing the multi widget: >>> from pprint import pprint >>> pprint(multiWidget.json_data()) {'error': '', 'id': '', 'label': '', 'mode': 'display', 'name': '', 'required': True, 'type': 'multi', 'value': ['3', '5', '8', '6', '42', '45'], 'widgets': [{'error': '', 'id': '-0', 'label': '', 'mode': 'display', 'name': '.0', 'required': True, 'type': 'text', 'value': '3'}, {'error': '', 'id': '-1', 'label': '', 'mode': 'display', 'name': '.1', 'required': True, 'type': 'text', 'value': '5'}, {'error': '', 'id': '-2', 'label': '', 'mode': 'display', 'name': '.2', 'required': True, 'type': 'text', 'value': '8'}, {'error': '', 'id': '-3', 'label': '', 'mode': 'display', 'name': '.3', 'required': True, 'type': 'text', 'value': '6'}, {'error': '', 'id': '-4', 'label': '', 'mode': 'display', 'name': '.4', 'required': True, 'type': 'text', 'value': '42'}, {'error': '', 'id': '-5', 'label': '', 'mode': 'display', 'name': '.5', 'required': True, 'type': 'text', 'value': '45'}]} Multi Dict Widget ----------------- We can also use a multiWidget in Dict mode by just using a field which a Dict: >>> multiField = zope.schema.Dict( ... key_type=zope.schema.Int(), ... value_type=zope.schema.Int(default=42)) >>> multiWidget.field = multiField >>> multiWidget.name = 'multi.name' Now if we set the value to a list we get an error: >>> multiWidget.value = ['3', '5', '8', '6', '42', '45'] Traceback (most recent call last): ... ValueError: need more than 1 value to unpack but a dictionary is good. >>> multiWidget.value = [('1', '3'), ('2', '5'), ('3', '8'), ('4', '6'), ('5', '42'), ('6', '45')] and our requests now have to include keys as well as values >>> multiWidget.request = TestRequest(form={'multi.name.count':'2', ... 'multi.name.key.0':'1', ... 'multi.name.0':'42', ... 'multi.name.key.1':'2', ... 'multi.name.1':'43'}) >>> multiWidget.extract() [('1', '42'), ('2', '43')] Let's define a field with min and max length constraints and create a widget for it. >>> multiField = zope.schema.Dict( ... key_type=zope.schema.Int(), ... value_type=zope.schema.Int(default=42), ... min_length=2, ... max_length=5) >>> request = TestRequest() >>> multiWidget = widget.FieldWidget(multiField, widget.MultiWidget(request)) Lets ensure that the minimum number of widgets are created. >>> multiWidget.update() >>> len(multiWidget.widgets) 2 We can add new items >>> multiWidget.appendAddingWidget() >>> multiWidget.appendAddingWidget() >>> multiWidget.update() >>> len(multiWidget.widgets) 4 The json data representing the Multi Dict Widget is the same as the Multi widget: Widget Events ------------- Widget-system interaction can be very rich and wants to be extended in unexpected ways. Thus there exists a generic widget event that can be used by other code. >>> event = widget.WidgetEvent(ageWidget) >>> event <WidgetEvent <Widget 'age'>> These events provide the ``IWidgetEvent`` interface: >>> interfaces.IWidgetEvent.providedBy(event) True There exists a special event that can be send out after a widget has been updated, ... >>> afterUpdate = widget.AfterWidgetUpdateEvent(ageWidget) >>> afterUpdate <AfterWidgetUpdateEvent <Widget 'age'>> which provides another special interface: >>> interfaces.IAfterWidgetUpdateEvent.providedBy(afterUpdate) True This event should be used by widget-managing components and is not created and sent out internally by the widget's ``update()`` method. The event was designed to provide an additional hook between updating the widget and rendering it. Cleanup ------- Let's not leave temporary files lying around >>> import os >>> os.remove(textWidgetTemplate)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/widget.rst
widget.rst
Password Widget --------------- The password widget allows you to upload a new password to the server. The "password" type of the "INPUT" element is described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-INPUT As for all widgets, the password widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import password >>> verifyClass(interfaces.IWidget, password.PasswordWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = password.PasswordWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget.id' >>> widget.name = 'widget.name' We also need to register the template for the widget: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('password_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IPasswordWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get a simple input element: >>> print(widget.render()) <input type="password" id="widget.id" name="widget.name" class="password-widget" /> Even when we set a value on the widget, it is not displayed for security reasons: >>> widget.value = 'password' >>> print(widget.render()) <input type="password" id="widget.id" name="widget.name" class="password-widget" /> Adding some more attributes to the widget will make it display more: >>> widget.style = u'color: blue' >>> widget.placeholder = u'Confirm password' >>> widget.autocapitalize = u'off' >>> print(widget.render()) <input type="password" id="widget.id" name="widget.name" placeholder="Confirm password" autocapitalize="off" style="color: blue" class="password-widget" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest(form={'widget.name': 'password'}) >>> widget.update() >>> widget.extract() 'password' If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/password.rst
password.rst
Multi Widget ------------ The multi widget allows you to add and edit one or more values. As for all widgets, the multi widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import multi >>> verifyClass(interfaces.IWidget, multi.MultiWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = multi.MultiWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('multi_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IMultiWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) For the next test, we need to setup our button handler adapters. >>> from z3c.form import button >>> zope.component.provideAdapter(button.ButtonActions) >>> zope.component.provideAdapter(button.ButtonActionHandler) >>> zope.component.provideAdapter(button.ButtonAction, ... provides=interfaces.IButtonAction) Our submit buttons will need a template as well: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('submit_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISubmitWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) We can now render the widget: >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="0" /> As you can see the widget is empty and doesn't provide values. This is because the widget does not know what sub-widgets to display. So let's register a `IFieldWidget` adapter and a template for our `IInt` field: >>> import z3c.form.interfaces >>> from z3c.form.browser.text import TextFieldWidget >>> zope.component.provideAdapter(TextFieldWidget, ... (zope.schema.interfaces.IInt, z3c.form.interfaces.IFormLayer)) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('text_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ITextWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) Let's now update the widget and check it again. >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="0" /> It's still the same. Since the widget doesn't provide a field nothing useful gets rendered. Now let's define a field for this widget and check it again: >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> <input type="hidden" name="widget.name.count" value="0" /> As you can see, there is still no input value. Let's provide some values for this widget. Before we can do that, we will need to register a data converter for our multi widget and the data converter dispatcher adapter: >>> from z3c.form.converter import IntegerDataConverter >>> from z3c.form.converter import FieldWidgetDataConverter >>> from z3c.form.validator import SimpleFieldValidator >>> zope.component.provideAdapter(IntegerDataConverter) >>> zope.component.provideAdapter(FieldWidgetDataConverter) >>> zope.component.provideAdapter(SimpleFieldValidator) >>> widget.value = ['42', '43'] >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> If we now click on the ``Add`` button, we will get a new input field for enter a new value: >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.0':'42', ... 'widget.name.1':'43', ... 'widget.name.buttons.add':'Add'}) >>> widget.update() >>> widget.extract() ['42', '43'] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div id="widget-id-2-row" class="row"> <div class="label"> <label for="widget-id-2"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-2-remove" name="widget.name.2.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-2" name="widget.name.2" class="text-widget required int-field" value="" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="3" /> Now let's store the new value: >>> widget.request = TestRequest(form={'widget.name.count':'3', ... 'widget.name.0':'42', ... 'widget.name.1':'43', ... 'widget.name.2':'44'}) >>> widget.update() >>> widget.extract() ['42', '43', '44'] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div id="widget-id-2-row" class="row"> <div class="label"> <label for="widget-id-2"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-2-remove" name="widget.name.2.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-2" name="widget.name.2" class="text-widget required int-field" value="44" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="3" /> As you can see in the above sample, the new stored value get rendered as a real value and the new adding value input field is gone. Now let's try to remove an existing value: >>> widget.request = TestRequest(form={'widget.name.count':'3', ... 'widget.name.0':'42', ... 'widget.name.1':'43', ... 'widget.name.2':'44', ... 'widget.name.1.remove':'1', ... 'widget.name.buttons.remove':'Remove selected'}) >>> widget.update() This is good so, because the Remove selected is an widget-internal submit action >>> widget.extract() ['42', '43', '44'] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="44" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> Change again a value after delete: >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.0':'42', ... 'widget.name.1':'45'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="widget-id-0-remove" name="widget.name.0.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <input id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" type="text" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="widget-id-1-remove" name="widget.name.1.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <input id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="45" type="text" /> </div> </div> </div> <div class="buttons"> <input id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> <input id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> Error handling is next. Let's use the value "bad" (an invalid integer literal) as input for our internal (sub) widget. >>> from z3c.form.error import ErrorViewSnippet >>> from z3c.form.error import StandardErrorViewTemplate >>> zope.component.provideAdapter(ErrorViewSnippet) >>> zope.component.provideAdapter(StandardErrorViewTemplate) >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.0':'42', ... 'widget.name.1':'bad'}) >>> widget.update() >>> widget.extract() ['42', 'bad'] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="bad" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> The widget filters out the add and remove buttons depending on the current value and the field constraints. You already saw that there's no remove button for empty value. Now, let's check rendering with minimum and maximum lengths defined in the field constraints. >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int(title='Number'), ... min_length=1, ... max_length=3 ... ) >>> widget.field = field >>> widget.widgets = [] >>> widget.value = [] Let's test with minimum sequence, there should be no remove button: >>> widget.request = TestRequest(form={'widget.name.count':'1', ... 'widget.name.0':'42'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> <input type="hidden" name="widget.name.count" value="1" /> Now, with middle-length sequence. All buttons should be there. >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.0':'42', ... 'widget.name.1':'43'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> Okay, now let's check the maximum-length sequence. There should be no add button: >>> widget.request = TestRequest(form={'widget.name.count':'3', ... 'widget.name.0':'42', ... 'widget.name.1':'43', ... 'widget.name.2':'44'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div id="widget-id-2-row" class="row"> <div class="label"> <label for="widget-id-2"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="widget-id-2-remove" name="widget.name.2.remove" /> </div> <div class="multi-widget-input"><input type="text" id="widget-id-2" name="widget.name.2" class="text-widget required int-field" value="44" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="3" /> Dictionaries ############ The multi widget also supports IDict schemas. >>> field = zope.schema.Dict( ... __name__='foo', ... key_type=zope.schema.Int(title='Number'), ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.widgets = [] >>> widget.value = [('1','42')] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-key-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-input-key"> <input id="widget-id-key-0" name="widget.name.key.0" class="text-widget required int-field" value="1" type="text" /> </div> </div> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="widget-id-0-remove" name="widget.name.0.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <input id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" type="text" /> </div> </div> </div> <div class="buttons"> <input id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input type="hidden" name="widget.name.count" value="1" /> If we now click on the ``Add`` button, we will get a new input field for entering a new value: >>> widget.request = TestRequest(form={'widget.name.count':'1', ... 'widget.name.key.0':'1', ... 'widget.name.0':'42', ... 'widget.name.buttons.add':'Add'}) >>> widget.update() >>> widget.extract() [('1', '42')] >>> print(widget.render()) <html> <body> <div class="multi-widget"> <div class="row" id="widget-id-0-row"> <div class="label"> <label for="widget-id-key-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-input-key"> <input class="text-widget required int-field" id="widget-id-key-0" name="widget.name.key.0" type="text" value="1"> </div> </div> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <input class="text-widget required int-field" id="widget-id-0" name="widget.name.0" type="text" value="42"> </div> </div> </div> <div class="row" id="widget-id-1-row"> <div class="label"> <label for="widget-id-key-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-input-key"> <input class="text-widget required int-field" id="widget-id-key-1" name="widget.name.key.1" type="text" value=""> </div> </div> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <input class="text-widget required int-field" id="widget-id-1" name="widget.name.1" type="text" value=""> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="widget-name-buttons-add" name="widget.name.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="widget-name-buttons-remove" name="widget.name.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="widget.name.count" type="hidden" value="2"> </body> </html> Now let's store the new value: >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.key.0':'1', ... 'widget.name.0':'42', ... 'widget.name.key.1':'2', ... 'widget.name.1':'43'}) >>> widget.update() >>> widget.extract() [('1', '42'), ('2', '43')] We will get an error if we try and set the same key twice >>> from z3c.form.error import InvalidErrorViewSnippet >>> zope.component.provideAdapter(InvalidErrorViewSnippet) >>> widget.request = TestRequest(form={'widget.name.count':'2', ... 'widget.name.key.0':'1', ... 'widget.name.0':'42', ... 'widget.name.key.1':'1', ... 'widget.name.1':'43'}) >>> widget.update() >>> widget.extract() [('1', '42'), ('1', '43')] >>> print(widget.render()) <div class="multi-widget"> <div id="widget-id-0-row" class="row"> <div class="label"> <label for="widget-id-key-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-input-key"> <input id="widget-id-key-0" name="widget.name.key.0" class="text-widget required int-field" value="1" type="text" /> </div> </div> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="widget-id-0-remove" name="widget.name.0.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <input id="widget-id-0" name="widget.name.0" class="text-widget required int-field" value="42" type="text" /> </div> </div> </div> <div id="widget-id-1-row" class="row"> <div class="label"> <label for="widget-id-key-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="error">Duplicate key</div> <div class="widget"> <div class="multi-widget-input-key"> <input id="widget-id-key-1" name="widget.name.key.1" class="text-widget required int-field" value="1" type="text" /> </div> </div> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="widget-id-1-remove" name="widget.name.1.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <input id="widget-id-1" name="widget.name.1" class="text-widget required int-field" value="43" type="text" /> </div> </div> </div> <div class="buttons"> <input id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> <input id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input type="hidden" name="widget.name.count" value="2" /> Displaying ########## The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = multi.MultiWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Set the mode to DISPLAY_MODE: >>> widget.mode = interfaces.DISPLAY_MODE We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('multi_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.IMultiWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) We can now render the widget: >>> widget.update() >>> print(widget.render()) <div class="multi-widget" id="widget-id"></div> As you can see the widget is empty and doesn't provide values. This is because the widget does not know what sub-widgets to display. So let's register a `IFieldWidget` adapter and a template for our `IInt` field: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('text_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.ITextWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) Let's now update the widget and check it again. >>> widget.update() >>> print(widget.render()) <div class="multi-widget" id="widget-id"></div> It's still the same. Since the widget doesn't provide a field nothing useful gets rendered. Now let's define a field for this widget and check it again: >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.update() >>> print(widget.render()) <div class="multi-widget" id="widget-id"></div> As you can see, there is still no input value. Let's provide some values for this widget. Before we can do that, we will need to register a data converter for our multi widget and the data converter dispatcher adapter: >>> widget.update() >>> widget.value = ['42', '43'] >>> print(widget.render()) <div class="multi-widget" id="widget-id"> <div class="row" id="widget-id-0-row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-0">42</span> </div> </div> </div> <div class="row" id="widget-id-1-row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-1">43</span> </div> </div> </div> </div> We can also use the multi widget with dictionaries >>> field = zope.schema.Dict( ... __name__='foo', ... key_type=zope.schema.Int(title='Number'), ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.value = [('1', '42'), ('2', '43')] >>> print(widget.render()) <div class="multi-widget" id="widget-id"> <div class="row" id="widget-id-0-row"> <div class="label"> <label for="widget-id-key-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-key-0">1</span> </div> </div> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-0">42</span> </div> </div> </div> <div class="row" id="widget-id-1-row"> <div class="label"> <label for="widget-id-key-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-key-1">2</span> </div> </div> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <span class="text-widget int-field" id="widget-id-1">43</span> </div> </div> </div> </div> Hidden mode ########### The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = multi.MultiWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Set the mode to HIDDEN_MODE: >>> widget.mode = interfaces.HIDDEN_MODE We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('multi_hidden.pt'), 'text/html'), ... (None, None, None, None, interfaces.IMultiWidget), ... IPageTemplate, name=interfaces.HIDDEN_MODE) We can now render the widget: >>> widget.update() >>> print(widget.render()) <input name="widget.name.count" type="hidden" value="0"> As you can see the widget is empty and doesn't provide values. This is because the widget does not know what sub-widgets to display. So let's register a `IFieldWidget` adapter and a template for our `IInt` field: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('text_hidden.pt'), 'text/html'), ... (None, None, None, None, interfaces.ITextWidget), ... IPageTemplate, name=interfaces.HIDDEN_MODE) Let's now update the widget and check it again. >>> widget.update() >>> print(widget.render()) <input name="widget.name.count" type="hidden" value="0"> It's still the same. Since the widget doesn't provide a field nothing useful gets rendered. Now let's define a field for this widget and check it again: >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.update() >>> print(widget.render()) <input name="widget.name.count" type="hidden" value="0"> As you can see, there is still no input value. Let's provide some values for this widget. Before we can do that, we will need to register a data converter for our multi widget and the data converter dispatcher adapter: >>> widget.update() >>> widget.value = ['42', '43'] >>> print(widget.render()) <input class="hidden-widget" id="widget-id-0" name="widget.name.0" type="hidden" value="42"> <input class="hidden-widget" id="widget-id-1" name="widget.name.1" type="hidden" value="43"> <input name="widget.name.count" type="hidden" value="2"> We can also use the multi widget with dictionaries >>> field = zope.schema.Dict( ... __name__='foo', ... key_type=zope.schema.Int(title='Number'), ... value_type=zope.schema.Int(title='Number'), ... ) >>> widget.field = field >>> widget.value = [('1', '42'), ('2', '43')] >>> print(widget.render()) <input class="hidden-widget" id="widget-id-key-0" name="widget.name.key.0" type="hidden" value="1"> <input class="hidden-widget" id="widget-id-0" name="widget.name.0" type="hidden" value="42"> <input class="hidden-widget" id="widget-id-key-1" name="widget.name.key.1" type="hidden" value="2"> <input class="hidden-widget" id="widget-id-1" name="widget.name.1" type="hidden" value="43"> <input name="widget.name.count" type="hidden" value="2"> Label ##### There is an option which allows to disable the label for the subwidgets. You can set the `showLabel` option to `False` which will skip rendering the labels. Alternatively you can also register your own template for your layer if you like to skip the label rendering for all widgets. One more way is to register an attribute adapter for specific field/widget/layer/etc. See below for an example. >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int( ... title='Ignored'), ... ) >>> request = TestRequest() >>> widget = multi.MultiWidget(request) >>> widget.field = field >>> widget.value = ['42', '43'] >>> widget.showLabel = False >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="None-0-row" class="row"> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="None-0-remove" name="None.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="None-0" name="None.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="None-1-row" class="row"> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="None-1-remove" name="None.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="None-1" name="None.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-buttons-add" name="widget.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-buttons-remove" name="widget.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="None.count" value="2" /> We can also override the showLabel attribute value with an attribute adapter. We set it to False for our widget before, but the update method sets adapted attributes, so if we provide an attribute, it will be used to set the ``showLabel``. Let's see. >>> from z3c.form.widget import StaticWidgetAttribute >>> doShowLabel = StaticWidgetAttribute(True, widget=widget) >>> zope.component.provideAdapter(doShowLabel, name="showLabel") >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div id="None-0-row" class="row"> <div class="label"> <label for="None-0"> <span>Ignored</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="None-0-remove" name="None.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="None-0" name="None.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="None-1-row" class="row"> <div class="label"> <label for="None-1"> <span>Ignored</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="None-1-remove" name="None.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="None-1" name="None.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="widget-buttons-add" name="widget.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-buttons-remove" name="widget.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="None.count" value="2" /> Coverage happiness ################## >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Int(title='Number'), ... ) >>> request = TestRequest() >>> widget = multi.MultiWidget(request) >>> widget.field = field >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' >>> widget.widgets = [] >>> widget.value = [] >>> widget.request = TestRequest() >>> widget.update() >>> widget.value = ['42', '43', '44'] >>> widget.value = ['99'] >>> print(widget.render()) <html> <body> <div class="multi-widget"> <div class="row" id="widget-id-0-row"> <div class="label"> <label for="widget-id-0"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="widget-id-0-remove" name="widget.name.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <input class="text-widget required int-field" id="widget-id-0" name="widget.name.0" type="text" value="99"> </div> </div> </div> <div class="row" id="widget-id-1-row"> <div class="label"> <label for="widget-id-1"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="widget-id-1-remove" name="widget.name.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <input class="text-widget required int-field" id="widget-id-1" name="widget.name.1" type="text" value=""> </div> </div> </div> <div class="row" id="widget-id-2-row"> <div class="label"> <label for="widget-id-2"> <span>Number</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="widget-id-2-remove" name="widget.name.2.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <input class="text-widget required int-field" id="widget-id-2" name="widget.name.2" type="text" value=""> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="widget-name-buttons-add" name="widget.name.buttons.add" type="submit" value="Add"> </div> </div> <input name="widget.name.count" type="hidden" value="3"> </body> </html>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/multi.rst
multi.rst
ObjectWidget integration with MultiWidget of list ------------------------------------------------- a.k.a. list of objects widget >>> from datetime import date >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import testing >>> from z3c.form.object import registerFactoryAdapter >>> registerFactoryAdapter(testing.IObjectWidgetMultiSubIntegration, ... testing.ObjectWidgetMultiSubIntegration) >>> request = testing.TestRequest() >>> class EForm(form.EditForm): ... form.extends(form.EditForm) ... fields = field.Fields( ... testing.IMultiWidgetListIntegration).select('listOfObject') Our multi content object: >>> obj = testing.MultiWidgetListIntegration() We recreate the form each time, to stay as close as possible. In real life the form gets instantiated and destroyed with each request. >>> def getForm(request, fname=None): ... frm = EForm(obj, request) ... testing.addTemplate(frm, 'integration_edit.pt') ... frm.update() ... content = frm.render() ... if fname is not None: ... testing.saveHtml(content, fname) ... return content Empty ##### All blank and empty values: >>> content = getForm(request, 'ObjectMulti_list_edit_empty.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> [Add] [Apply] Some valid default values ######################### >>> sub1 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=-100, ... multiBool=False, ... multiChoice='two', ... multiChoiceOpt='six', ... multiTextLine='some text one', ... multiDate=date(2014, 6, 20)) >>> sub2 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=42, ... multiBool=True, ... multiChoice='one', ... multiChoiceOpt='four', ... multiTextLine='second txt', ... multiDate=date(2011, 3, 15)) >>> obj.listOfObject = [sub1, sub2] >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>] >>> content = getForm(request, 'ObjectMulti_list_edit_simple.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * [ ] Int label * [-100] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] Object label * [ ] Int label * [42] Bool label * (O) yes ( ) no Choice label * [one] ChoiceOpt label [four] TextLine label * [second txt] Date label * [11/03/15] [Add] [Remove selected] [Apply] wrong input (Int) ################# Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiInt'] = 'foobar' >>> submit['form.widgets.listOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The entered value is not a valid integer literal." for "foobar" and a new input. >>> content = getForm(request, 'ObjectMulti_list_edit_submit_int.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-0-row"]')) Object label * <BLANKLINE> The entered value is not a valid integer literal. <BLANKLINE> [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_submit_int_again.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-0-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-1-row"]//div[@class="error"]')) >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-2-row"]')) Object label * <BLANKLINE> An object failed schema or invariant validation. <BLANKLINE> [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * Required input is missing. [] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.1.remove'] = '1' >>> submit['form.widgets.listOfObject.2.remove'] = '1' >>> submit['form.widgets.listOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_remove_int.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>] wrong input (TextLine) ###################### Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiTextLine'] = 'foo\nbar' >>> submit['form.widgets.listOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "Constraint not satisfied" for "foo\nbar" and a new input. >>> content = getForm(request, 'ObjectMulti_list_edit_submit_textline.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-0-row"]')) Object label * <BLANKLINE> The entered value is not a valid integer literal. <BLANKLINE> [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * [14/06/20] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_submit_textline_again.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-0-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. Constraint not satisfied >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-1-row"]//div[@class="error"]')) An object failed schema or invariant validation. Required input is missing. Required input is missing. Required input is missing. Required input is missing. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.1.remove'] = '1' >>> submit['form.widgets.listOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_remove_textline.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * [14/06/20] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>] wrong input (Date) ################## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiDate'] = 'foobar' >>> submit['form.widgets.listOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The datetime string did not match the pattern" for "foobar" and a new input. >>> content = getForm(request, 'ObjectMulti_list_edit_submit_date.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] Object label * [ ] Int label * [] Bool label * ( ) yes ( ) no Choice label * [[ ]] ChoiceOpt label [No value] TextLine label * [] Date label * [] [Add] [Remove selected] [Apply] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content, ... './/div[@id="form-widgets-listOfObject-0-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. Constraint not satisfied The datetime string did not match the pattern 'yy/MM/dd'. Add one more field: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) And fill in a valid value: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.2.widgets.multiDate'] = '14/06/21' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_submit_date2.html') >>> print(testing.plainText(content)) ListOfObject label Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] Object label * An object failed schema or invariant validation. [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * Required input is missing. [] Object label * An object failed schema or invariant validation. [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * [14/06/21] [Add] [Remove selected] [Apply] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.2.remove'] = '1' >>> submit['form.widgets.listOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_remove_date.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] Object label * An object failed schema or invariant validation. [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * Required input is missing. [] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>] Fix values ########## >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiInt'] = '1042' >>> submit['form.widgets.listOfObject.0.widgets.multiTextLine'] = 'moo900' >>> submit['form.widgets.listOfObject.0.widgets.multiDate'] = '14/06/23' >>> submit['form.widgets.listOfObject.1.remove'] = '1' >>> submit['form.widgets.listOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_list_edit_fix_values.html') >>> print(testing.plainText(content)) ListOfObject label <BLANKLINE> Object label * [ ] Int label * [1,042] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [moo900] Date label * [14/06/23] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>] And apply >>> submit = testing.getSubmitValues(content) >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. <BLANKLINE> ListOfObject label <BLANKLINE> Object label * [ ] Int label * [1,042] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [moo900] Date label * [14/06/23] [Add] [Remove selected] [Apply] Now the object gets updated: >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 23) multiInt: 1042 multiTextLine: 'moo900'>] Bool was misbehaving #################### >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiBool'] = 'true' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 23) multiInt: 1042 multiTextLine: 'moo900'>] >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfObject.0.widgets.multiBool'] = 'false' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.listOfObject) [<ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 23) multiInt: 1042 multiTextLine: 'moo900'>]
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/object_multi_list_integration.rst
object_multi_list_integration.rst
Ordered-Select Widget --------------------- The ordered select widget allows you to select one or more values from a set of given options and sort those options. Unfortunately, HTML does not provide such a widget as part of its specification, so that the system has to use a combnation of "option" elements, buttons and Javascript. As for all widgets, the select widget must provide the new ``IWidget`` interface: >>> from zope.interface import verify >>> from z3c.form import interfaces >>> from z3c.form.browser import orderedselect >>> verify.verifyClass(interfaces.IWidget, orderedselect.OrderedSelectWidget) True The widget can be instantiated only using the request: >>> from z3c.form import testing >>> request = testing.TestRequest() >>> widget = orderedselect.OrderedSelectWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('orderedselect_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IOrderedSelectWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get an empty widget: >>> print(widget.render()) <script type="text/javascript" src="++resource++orderedselect_input.js" /> <table border="0" class="ordered-selection-field" id="widget-id"> <tr> <td> <select id="widget-id-from" name="widget.name.from" size="5" multiple="multiple"> </select> </td> <td> <button name="from2toButton" type="button" value="&rarr;" onclick="javascript:from2to('widget-id')">&rarr;</button> <br /> <button name="to2fromButton" type="button" value="&larr;" onclick="javascript:to2from('widget-id')">&larr;</button> </td> <td> <select id="widget-id-to" name="widget.name.to" size="5" multiple="multiple"> </select> <input name="widget.name-empty-marker" type="hidden" /> <span id="widget-id-toDataContainer" style="display: none"> <script type="text/javascript"> copyDataForSubmit('widget-id');</script> </span> </td> <td> <button name="upButton" type="button" value="&uarr;" onclick="javascript:moveUp('widget-id')">&uarr;</button> <br /> <button name="downButton" type="button" value="&darr;" onclick="javascript:moveDown('widget-id')">&darr;</button> </td> </tr> </table> The json data representing the oredered select widget: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'notSelected': (), 'options': (), 'required': False, 'selected': (), 'type': 'multiSelect', 'value': ()} Let's provide some values for this widget. We can do this by defining a source providing ``ITerms``. This source uses descriminators wich will fit our setup. >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary >>> import z3c.form.term >>> class SelectionTerms(z3c.form.term.Terms): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary([ ... SimpleVocabulary.createTerm(1, 'a', u'A'), ... SimpleVocabulary.createTerm(2, 'b', u'B'), ... SimpleVocabulary.createTerm(3, 'c', u'C'), ... SimpleVocabulary.createTerm(4, 'd', u'A'), ... ]) >>> zope.component.provideAdapter(SelectionTerms, ... (None, interfaces.IFormLayer, None, None, ... interfaces.IOrderedSelectWidget) ) Now let's try if we get widget values: >>> widget.update() >>> print(testing.render(widget, './/table//td[1]')) <td> <select id="widget-id-from" name="widget.name.from" size="5" multiple="multiple"> <option value="a">A</option> <option value="b">B</option> <option value="c">C</option> <option value="d">A</option> </select> </td> If we select item "b", then it should be selected: >>> widget.value = ['b'] >>> widget.update() >>> print(testing.render(widget, './/table//select[@id="widget-id-from"]/..')) <td> <select id="widget-id-from" name="widget.name.from" size="5" multiple="multiple"> <option value="a">A</option> <option value="c">C</option> <option value="d">A</option> </select> </td> >>> print(testing.render(widget, './/table//select[@id="widget-id-to"]')) <select id="widget-id-to" name="widget.name.to" size="5" multiple="multiple"> <option value="b">B</option> </select> The json data representing the oredered select widget: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'notSelected': [{'content': 'A', 'id': 'widget-id-0', 'value': 'a'}, {'content': 'C', 'id': 'widget-id-2', 'value': 'c'}, {'content': 'A', 'id': 'widget-id-3', 'value': 'd'}], 'options': [{'content': 'A', 'id': 'widget-id-0', 'value': 'a'}, {'content': 'B', 'id': 'widget-id-1', 'value': 'b'}, {'content': 'C', 'id': 'widget-id-2', 'value': 'c'}, {'content': 'A', 'id': 'widget-id-3', 'value': 'd'}], 'required': False, 'selected': [{'content': 'B', 'id': 'widget-id-0', 'value': 'b'}], 'type': 'multiSelect', 'value': ['b']} Let's now make sure that we can extract user entered data from a widget: >>> widget.request = testing.TestRequest(form={'widget.name': ['c']}) >>> widget.update() >>> widget.extract() ('c',) Unfortunately, when nothing is selected, we do not get an empty list sent into the request, but simply no entry at all. For this we have the empty marker, so that: >>> widget.request = testing.TestRequest(form={'widget.name-empty-marker': '1'}) >>> widget.update() >>> widget.extract() () If nothing is found in the request, the default is returned: >>> widget.request = testing.TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE> Let's now make sure that a bogus value causes extract to return the default as described by the interface: >>> widget.request = testing.TestRequest(form={'widget.name': ['x']}) >>> widget.update() >>> widget.extract() <NO_VALUE> Finally, let's check correctness of widget rendering in one rare case when we got selection terms with callable values and without titles. For example, you can get those terms when you using the "Content Types" vocabulary from zope.app.content. >>> class CallableValue(object): ... def __init__(self, value): ... self.value = value ... def __call__(self): ... pass ... def __str__(self): ... return 'Callable Value %s' % self.value >>> class SelectionTermsWithCallableValues(z3c.form.term.Terms): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary([ ... SimpleVocabulary.createTerm(CallableValue(1), 'a'), ... SimpleVocabulary.createTerm(CallableValue(2), 'b'), ... SimpleVocabulary.createTerm(CallableValue(3), 'c') ... ]) >>> widget.terms = SelectionTermsWithCallableValues( ... None, testing.TestRequest(), None, None, widget) >>> widget.update() >>> print(testing.render(widget, './/table//select[@id="widget-id-from"]')) <select id="widget-id-from" name="widget.name.from" size="5" multiple="multiple"> <option value="a">Callable Value 1</option> <option value="b">Callable Value 2</option> <option value="c">Callable Value 3</option> </select>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/orderedselect.rst
orderedselect.rst
Submit Widget ------------- The submit widget allows you to upload a new submit to the server. The "submit" type of the "INPUT" element is described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-INPUT As for all widgets, the submit widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import submit >>> verifyClass(interfaces.IWidget, submit.SubmitWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = submit.SubmitWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget.id' >>> widget.name = 'widget.name' We also need to register the template for the widget: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('submit_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISubmitWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get a simple input element: >>> print(widget.render()) <input type="submit" id="widget.id" name="widget.name" class="submit-widget" /> Setting a value for the widget effectively changes the button label: >>> widget.value = 'Submit' >>> print(widget.render()) <input type="submit" id="widget.id" name="widget.name" class="submit-widget" value="Submit" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest(form={'widget.name': 'submit'}) >>> widget.update() >>> widget.extract() 'submit' If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/submit.rst
submit.rst
Multi+Object Widget ------------------- The multi widget allows you to add and edit one or more values. In order to not overwhelm you with our set of well-chosen defaults, all the default component registrations have been made prior to doing those examples: >>> from z3c.form import testing >>> testing.setupFormDefaults() As for all widgets, the multi widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import multi >>> verifyClass(interfaces.IWidget, multi.MultiWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = multi.MultiWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('multi_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IMultiWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('multi_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.IMultiWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) For the next test, we need to setup our button handler adapters. >>> from z3c.form import button >>> zope.component.provideAdapter(button.ButtonActions) >>> zope.component.provideAdapter(button.ButtonActionHandler) >>> zope.component.provideAdapter(button.ButtonAction, ... provides=interfaces.IButtonAction) Our submit buttons will need a template as well: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('submit_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISubmitWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) We can now render the widget: >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="0" /> As you can see the widget is empty and doesn't provide values. This is because the widget does not know what sub-widgets to display. So let's register a `IFieldWidget` adapter and a template for our `IInt` field: >>> import z3c.form.interfaces >>> from z3c.form.browser.text import TextFieldWidget >>> zope.component.provideAdapter(TextFieldWidget, ... (zope.schema.interfaces.IInt, z3c.form.interfaces.IFormLayer)) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('text_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ITextWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) Let's now update the widget and check it again. >>> widget.update() >>> print(widget.render()) <div class="multi-widget"> <div class="buttons"> <input type="submit" id="widget-name-buttons-add" name="widget.name.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="widget-name-buttons-remove" name="widget.name.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="widget.name.count" value="0" /> It's still the same. Since the widget doesn't provide a field nothing useful gets rendered. Now let's define a field for this widget and check it again: >>> from z3c.form.widget import FieldWidget >>> from z3c.form.testing import IMySubObjectMulti >>> from z3c.form.testing import MySubObjectMulti >>> from z3c.form.object import registerFactoryAdapter >>> registerFactoryAdapter(IMySubObjectMulti, MySubObjectMulti) >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Object(title=u'my object widget', ... schema=IMySubObjectMulti), ... ) >>> widget = FieldWidget(field, widget) >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="buttons"> <input type="submit" id="foo-buttons-add" name="foo.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> <input type="hidden" name="foo.count" value="0" /> As you can see, there is still no input value. Let's provide some values for this widget. Before we can do that, we will need to register a data converter for our multi widget and the data converter dispatcher adapter: >>> from z3c.form.converter import IntegerDataConverter >>> from z3c.form.converter import FieldWidgetDataConverter >>> from z3c.form.converter import MultiConverter >>> from z3c.form.validator import SimpleFieldValidator >>> zope.component.provideAdapter(IntegerDataConverter) >>> zope.component.provideAdapter(FieldWidgetDataConverter) >>> zope.component.provideAdapter(SimpleFieldValidator) >>> zope.component.provideAdapter(MultiConverter) Bunch of adapters to get objectwidget work: >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.DictionaryField) >>> import z3c.form.browser.object >>> zope.component.provideAdapter(z3c.form.browser.object.ObjectFieldWidget) >>> import z3c.form.object >>> zope.component.provideAdapter(z3c.form.object.ObjectConverter) >>> import z3c.form.error >>> zope.component.provideAdapter(z3c.form.error.ValueErrorViewSnippet) >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('object_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IObjectWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('object_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.IObjectWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) >>> widget.update() It must not fail if we assign values that do not meet the constraints, just cry about it in the HTML: >>> widget.value = [z3c.form.object.ObjectWidgetValue( ... {'foofield': u'', 'barfield': '666'})] >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="error">An object failed schema or invariant validation.</div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="error">Required input is missing.</div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value=""> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input id="foo-buttons-add" name="foo.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> <input id="foo-buttons-remove" name="foo.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input name="foo.count" type="hidden" value="1"> Let's set acceptable values: >>> widget.value = [ ... z3c.form.object.ObjectWidgetValue(dict(foofield=u'42', barfield=u'666')), ... z3c.form.object.ObjectWidgetValue(dict(foofield=u'789', barfield=u'321'))] >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="foo-0-remove" name="foo.0.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" class="text-widget required int-field" value="42" type="text" /> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" class="text-widget int-field" value="666" type="text" /> </div> <input name="foo.0-empty-marker" type="hidden" value="1" /> </div> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input id="foo-1-remove" name="foo.1.remove" class="multi-widget-checkbox checkbox-widget" type="checkbox" value="1" /> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" class="text-widget required int-field" value="789" type="text" /> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" class="text-widget int-field" value="321" type="text" /> </div> <input name="foo.1-empty-marker" type="hidden" value="1" /> </div> </div> </div> </div> <div class="buttons"> <input id="foo-buttons-add" name="foo.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> <input id="foo-buttons-remove" name="foo.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input type="hidden" name="foo.count" value="2" /> Let's see what we get on value extraction: >>> widget.extract() <NO_VALUE> If we now click on the ``Add`` button, we will get a new input field for enter a new value: >>> widget.request = TestRequest(form={'foo.count':u'2', ... 'foo.0.widgets.foofield':u'42', ... 'foo.0.widgets.barfield':u'666', ... 'foo.0-empty-marker':u'1', ... 'foo.1.widgets.foofield':u'789', ... 'foo.1.widgets.barfield':u'321', ... 'foo.1-empty-marker':u'1', ... 'foo.buttons.add':'Add'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-1-row"> <div class="label"> <label for="foo-1"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="foo.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" type="text" value="789"> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" type="text" value="321"> </div> <input name="foo.1-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-2-row"> <div class="label"> <label for="foo-2"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-2-remove" name="foo.2.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-2-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-2-widgets-foofield" name="foo.2.widgets.foofield" type="text" value=""> </div> <div class="label"> <label for="foo-2-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-2-widgets-barfield" name="foo.2.widgets.barfield" type="text" value="2,222"> </div> <input name="foo.2-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input id="foo-buttons-add" name="foo.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> <input id="foo-buttons-remove" name="foo.buttons.remove" class="submit-widget button-field" value="Remove selected" type="submit" /> </div> </div> <input name="foo.count" type="hidden" value="3"> Let's see what we get on value extraction: >>> value = widget.extract() >>> pprint(value) [{'barfield': '666', 'foofield': '42'}, {'barfield': '321', 'foofield': '789'}] >>> converter = interfaces.IDataConverter(widget) >>> value = converter.toFieldValue(value) >>> value [<z3c.form.testing.MySubObjectMulti object at ...>, <z3c.form.testing.MySubObjectMulti object at ...>] >>> value[0].foofield 42 >>> value[0].barfield 666 Now let's store the new value: >>> widget.request = TestRequest(form={'foo.count':u'3', ... 'foo.0.widgets.foofield':u'42', ... 'foo.0.widgets.barfield':u'666', ... 'foo.0-empty-marker':u'1', ... 'foo.1.widgets.foofield':u'789', ... 'foo.1.widgets.barfield':u'321', ... 'foo.1-empty-marker':u'1', ... 'foo.2.widgets.foofield':u'46', ... 'foo.2.widgets.barfield':u'98', ... 'foo.2-empty-marker':u'1', ... }) >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-1-row"> <div class="label"> <label for="foo-1"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="foo.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" type="text" value="789"> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" type="text" value="321"> </div> <input name="foo.1-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-2-row"> <div class="label"> <label for="foo-2"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-2-remove" name="foo.2.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-2-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-2-widgets-foofield" name="foo.2.widgets.foofield" type="text" value="46"> </div> <div class="label"> <label for="foo-2-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-2-widgets-barfield" name="foo.2.widgets.barfield" type="text" value="98"> </div> <input name="foo.2-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="foo-buttons-add" name="foo.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="foo-buttons-remove" name="foo.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="foo.count" type="hidden" value="3"> Let's see what we get on value extraction: >>> value = widget.extract() >>> pprint(value) [{'barfield': '666', 'foofield': '42'}, {'barfield': '321', 'foofield': '789'}, {'barfield': '98', 'foofield': '46'}] >>> converter = interfaces.IDataConverter(widget) >>> value = converter.toFieldValue(value) >>> value [<z3c.form.testing.MySubObjectMulti object at ...>, <z3c.form.testing.MySubObjectMulti object at ...>] >>> value[0].foofield 42 >>> value[0].barfield 666 As you can see in the above sample, the new stored value gets rendered as a real value and the new adding value input field is gone. Now let's try to remove an existing value: >>> widget.request = TestRequest(form={'foo.count':u'3', ... 'foo.0.widgets.foofield':u'42', ... 'foo.0.widgets.barfield':u'666', ... 'foo.0-empty-marker':u'1', ... 'foo.1.widgets.foofield':u'789', ... 'foo.1.widgets.barfield':u'321', ... 'foo.1-empty-marker':u'1', ... 'foo.2.widgets.foofield':u'46', ... 'foo.2.widgets.barfield':u'98', ... 'foo.2-empty-marker':u'1', ... 'foo.1.remove':u'1', ... 'foo.buttons.remove':'Remove selected'}) >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-1-row"> <div class="label"> <label for="foo-1"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="foo.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" type="text" value="46"> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" type="text" value="98"> </div> <input name="foo.1-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="foo-buttons-add" name="foo.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="foo-buttons-remove" name="foo.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="foo.count" type="hidden" value="2"> Let's see what we get on value extraction: (this is good so, because Remove selected is a widget-internal submit) >>> value = widget.extract() >>> pprint(value) [{'barfield': '666', 'foofield': '42'}, {'barfield': '321', 'foofield': '789'}, {'barfield': '98', 'foofield': '46'}] >>> converter = interfaces.IDataConverter(widget) >>> value = converter.toFieldValue(value) >>> value [<z3c.form.testing.MySubObjectMulti object at ...>, <z3c.form.testing.MySubObjectMulti object at ...>] >>> value[0].foofield 42 >>> value[0].barfield 666 Error handling is next. Let's use the value "bad" (an invalid integer literal) as input for our internal (sub) widget. >>> from z3c.form.error import ErrorViewSnippet >>> from z3c.form.error import StandardErrorViewTemplate >>> zope.component.provideAdapter(ErrorViewSnippet) >>> zope.component.provideAdapter(StandardErrorViewTemplate) >>> widget.request = TestRequest(form={'foo.count':u'2', ... 'foo.0.widgets.foofield':u'42', ... 'foo.0.widgets.barfield':u'666', ... 'foo.0-empty-marker':u'1', ... 'foo.1.widgets.foofield':u'bad', ... 'foo.1.widgets.barfield':u'98', ... 'foo.1-empty-marker':u'1', ... }) >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="label"> <label for="foo-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-1-row"> <div class="label"> <label for="foo-1"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="foo.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <input class="text-widget required int-field" id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" type="text" value="bad"> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" type="text" value="98"> </div> <input name="foo.1-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="foo-buttons-add" name="foo.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="foo-buttons-remove" name="foo.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="foo.count" type="hidden" value="2"> Let's see what we get on value extraction: >>> value = widget.extract() >>> pprint(value) [{'barfield': '666', 'foofield': '42'}, {'barfield': '98', 'foofield': 'bad'}] Label ##### There is an option which allows to disable the label for the (sub) widgets. You can set the `showLabel` option to `False` which will skip rendering the labels. Alternatively you can also register your own template for your layer if you like to skip the label rendering for all widgets. >>> field = zope.schema.List( ... __name__='foo', ... value_type=zope.schema.Object(title=u'ignored_title', ... schema=IMySubObjectMulti), ... ) >>> request = TestRequest() >>> widget = multi.MultiWidget(request) >>> widget = FieldWidget(field, widget) >>> widget.value = [ ... z3c.form.object.ObjectWidgetValue(dict(foofield='42', barfield='666')), ... z3c.form.object.ObjectWidgetValue(dict(foofield='789', barfield='321'))] >>> widget.showLabel = False >>> widget.update() >>> print(widget.render()) <div class="multi-widget required"> <div class="row" id="foo-0-row"> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="foo.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-0-widgets-foofield" name="foo.0.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="foo-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-0-widgets-barfield" name="foo.0.widgets.barfield" type="text" value="666"> </div> <input name="foo.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="row" id="foo-1-row"> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="foo.1.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="foo-1-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="foo-1-widgets-foofield" name="foo.1.widgets.foofield" type="text" value="789"> </div> <div class="label"> <label for="foo-1-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="foo-1-widgets-barfield" name="foo.1.widgets.barfield" type="text" value="321"> </div> <input name="foo.1-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="foo-buttons-add" name="foo.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="foo-buttons-remove" name="foo.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="foo.count" type="hidden" value="2"> In a form ######### Let's try a simple example in a form. We have to provide an adapter first: >>> import z3c.form.browser.object >>> zope.component.provideAdapter(z3c.form.browser.object.ObjectFieldWidget) Forms and our objectwidget fire events on add and edit, setup a subscriber for those: >>> eventlog = [] >>> import zope.lifecycleevent >>> @zope.component.adapter(zope.lifecycleevent.ObjectModifiedEvent) ... def logEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent) >>> @zope.component.adapter(zope.lifecycleevent.ObjectCreatedEvent) ... def logEvent2(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent2) >>> def printEvents(): ... for event in eventlog: ... print(event) ... if isinstance(event, zope.lifecycleevent.ObjectModifiedEvent): ... for attr in event.descriptions: ... print(attr.interface) ... print(sorted(attr.attributes)) We need to provide the widgets for the List >>> from z3c.form.browser.multi import multiFieldWidgetFactory >>> zope.component.provideAdapter(multiFieldWidgetFactory, ... (zope.schema.interfaces.IList, z3c.form.interfaces.IFormLayer)) >>> zope.component.provideAdapter(multiFieldWidgetFactory, ... (zope.schema.interfaces.ITuple, z3c.form.interfaces.IFormLayer)) >>> zope.component.provideAdapter(multiFieldWidgetFactory, ... (zope.schema.interfaces.IDict, z3c.form.interfaces.IFormLayer)) We define an interface containing a subobject, and an addform for it: >>> from z3c.form import form, field >>> from z3c.form.testing import MyMultiObject, IMyMultiObject Note, that creating an object will print some information about it: >>> class MyAddForm(form.AddForm): ... fields = field.Fields(IMyMultiObject) ... def create(self, data): ... print("MyAddForm.create") ... pprint(data) ... return MyMultiObject(**data) ... def add(self, obj): ... self.context[obj.name] = obj ... def nextURL(self): ... pass We create the form and try to update it: >>> request = TestRequest() >>> myaddform = MyAddForm(root, request) >>> myaddform.update() As usual, the form contains a widget manager with the expected widget >>> list(myaddform.widgets.keys()) ['listOfObject', 'name'] >>> list(myaddform.widgets.values()) [<MultiWidget 'form.widgets.listOfObject'>, <TextWidget 'form.widgets.name'>] If we want to render the addform, we must give it a template: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate >>> from z3c.form import tests >>> def addTemplate(form): ... form.template = BoundPageTemplate( ... ViewPageTemplateFile( ... 'simple_edit.pt', os.path.dirname(tests.__file__)), form) >>> addTemplate(myaddform) Now rendering the addform renders no items yet: >>> print(myaddform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget required"> <div class="buttons"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-add" name="form.widgets.listOfObject.buttons.add" type="submit" value="Add"> </div> </div> <input name="form.widgets.listOfObject.count" type="hidden" value="0"> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value=""> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-add" name="form.buttons.add" type="submit" value="Add"> </div> </form> </body> </html> We don't have the object (yet) in the root: >>> root['first'] Traceback (most recent call last): ... KeyError: 'first' Add a row to the multi widget: >>> request = TestRequest(form={ ... 'form.widgets.listOfObject.count':u'0', ... 'form.widgets.listOfObject.buttons.add':'Add'}) >>> myaddform.request = request Update with the request: >>> myaddform.update() Render the form: >>> print(myaddform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget required"> <div class="row" id="form-widgets-listOfObject-0-row"> <div class="label"> <label for="form-widgets-listOfObject-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="form-widgets-listOfObject-0-remove" name="form.widgets.listOfObject.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-listOfObject-0-widgets-foofield" name="form.widgets.listOfObject.0.widgets.foofield" type="text" value=""> </div> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-barfield" name="form.widgets.listOfObject.0.widgets.barfield" type="text" value="2,222"> </div> <input name="form.widgets.listOfObject.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-add" name="form.widgets.listOfObject.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-remove" name="form.widgets.listOfObject.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="form.widgets.listOfObject.count" type="hidden" value="1"> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value=""> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-add" name="form.buttons.add" type="submit" value="Add"> </div> </form> </body> </html> Now we can fill in some values to the object, and a name to the whole schema: >>> request = TestRequest(form={ ... 'form.widgets.listOfObject.count':u'1', ... 'form.widgets.listOfObject.0.widgets.foofield':u'66', ... 'form.widgets.listOfObject.0.widgets.barfield':u'99', ... 'form.widgets.listOfObject.0-empty-marker':u'1', ... 'form.widgets.name':u'first', ... 'form.buttons.add':'Add'}) >>> myaddform.request = request Update the form with the request: >>> myaddform.update() MyAddForm.create {'listOfObject': [<z3c.form.testing.MySubObjectMulti ...], 'name': 'first'} Wow, it got added: >>> root['first'] <z3c.form.testing.MyMultiObject object at ...> >>> root['first'].listOfObject [<z3c.form.testing.MySubObjectMulti object at ...>] Field values need to be right: >>> root['first'].listOfObject[0].foofield 66 >>> root['first'].listOfObject[0].barfield 99 Let's see our event log: >>> len(eventlog) 6 ((why is IMySubObjectMulti created twice???)) >>> printEvents() <zope...ObjectCreatedEvent object at ...> <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObjectMulti ['barfield', 'foofield'] <zope...ObjectCreatedEvent object at ...> <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObjectMulti ['barfield', 'foofield'] <zope...ObjectCreatedEvent object at ...> <zope...contained.ContainerModifiedEvent object at ...> >>> eventlog=[] Let's try to edit that newly added object: >>> class MyEditForm(form.EditForm): ... fields = field.Fields(IMyMultiObject) >>> editform = MyEditForm(root['first'], TestRequest()) >>> addTemplate(editform) >>> editform.update() Watch for the widget values in the HTML: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget required"> <div class="row" id="form-widgets-listOfObject-0-row"> <div class="label"> <label for="form-widgets-listOfObject-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="form-widgets-listOfObject-0-remove" name="form.widgets.listOfObject.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-listOfObject-0-widgets-foofield" name="form.widgets.listOfObject.0.widgets.foofield" type="text" value="66"> </div> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-barfield" name="form.widgets.listOfObject.0.widgets.barfield" type="text" value="99"> </div> <input name="form.widgets.listOfObject.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-add" name="form.widgets.listOfObject.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-remove" name="form.widgets.listOfObject.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="form.widgets.listOfObject.count" type="hidden" value="1"> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's modify the values: >>> request = TestRequest(form={ ... 'form.widgets.listOfObject.count':u'1', ... 'form.widgets.listOfObject.0.widgets.foofield':u'43', ... 'form.widgets.listOfObject.0.widgets.barfield':u'55', ... 'form.widgets.listOfObject.0-empty-marker':u'1', ... 'form.widgets.name':u'first', ... 'form.buttons.apply':'Apply'}) They are still the same: >>> root['first'].listOfObject[0].foofield 66 >>> root['first'].listOfObject[0].barfield 99 >>> editform.request = request >>> editform.update() Until we have updated the form: >>> root['first'].listOfObject[0].foofield 43 >>> root['first'].listOfObject[0].barfield 55 Let's see our event log: >>> len(eventlog) 5 ((TODO: now this is real crap here, why is IMySubObjectMulti created 3 times???)) >>> printEvents() <zope...ObjectCreatedEvent object at ...> <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObjectMulti ['barfield', 'foofield'] <zope...ObjectCreatedEvent object at ...> <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObjectMulti ['barfield', 'foofield'] <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMyMultiObject ['listOfObject'] >>> eventlog=[] After the update the form says that the values got updated and renders the new values: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>Data successfully updated.</i> <form action="."> <div class="row"> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget required"> <div class="row" id="form-widgets-listOfObject-0-row"> <div class="label"> <label for="form-widgets-listOfObject-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="form-widgets-listOfObject-0-remove" name="form.widgets.listOfObject.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-listOfObject-0-widgets-foofield" name="form.widgets.listOfObject.0.widgets.foofield" type="text" value="43"> </div> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-barfield" name="form.widgets.listOfObject.0.widgets.barfield" type="text" value="55"> </div> <input name="form.widgets.listOfObject.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-add" name="form.widgets.listOfObject.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-remove" name="form.widgets.listOfObject.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="form.widgets.listOfObject.count" type="hidden" value="1"> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's see if the widget keeps the old object on editing: We add a special property to keep track of the object: >>> root['first'].listOfObject[0].__marker__ = "ThisMustStayTheSame" >>> root['first'].listOfObject[0].foofield 43 >>> root['first'].listOfObject[0].barfield 55 Let's modify the values: >>> request = TestRequest(form={ ... 'form.widgets.listOfObject.count':u'1', ... 'form.widgets.listOfObject.0.widgets.foofield':u'666', ... 'form.widgets.listOfObject.0.widgets.barfield':u'999', ... 'form.widgets.listOfObject.0-empty-marker':u'1', ... 'form.widgets.name':u'first', ... 'form.buttons.apply':'Apply'}) >>> editform.request = request >>> editform.update() Let's check what are ther esults of the update: >>> root['first'].listOfObject[0].foofield 666 >>> root['first'].listOfObject[0].barfield 999 ((TODO: bummer... we can't keep the old object)) #>>> root['first'].listOfObject[0].__marker__ #'ThisMustStayTheSame' Let's make a nasty error, by typing 'bad' instead of an integer: >>> request = TestRequest(form={ ... 'form.widgets.listOfObject.count':u'1', ... 'form.widgets.listOfObject.0.widgets.foofield':u'99', ... 'form.widgets.listOfObject.0.widgets.barfield':u'bad', ... 'form.widgets.listOfObject.0-empty-marker':u'1', ... 'form.widgets.name':u'first', ... 'form.buttons.apply':'Apply'}) >>> editform.request = request >>> eventlog=[] >>> editform.update() Eventlog must be clean: >>> len(eventlog) 2 ((TODO: bummer... who creates those 2 objects???)) >>> printEvents() <zope...ObjectCreatedEvent object at ...> <zope...ObjectCreatedEvent object at ...> Watch for the error message in the HTML: it has to appear at the field itself and at the top of the form: ((not nice: at the top ``Object is of wrong type.`` appears)) >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> My list field: <div class="error">The entered value is not a valid integer literal.</div> </li> </ul> <form action="."> <div class="row"> <b> <div class="error">The entered value is not a valid integer literal.</div> </b> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget required"> <div class="row" id="form-widgets-listOfObject-0-row"> <div class="label"> <label for="form-widgets-listOfObject-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <div class="multi-widget-checkbox"> <input class="multi-widget-checkbox checkbox-widget" id="form-widgets-listOfObject-0-remove" name="form.widgets.listOfObject.0.remove" type="checkbox" value="1"> </div> <div class="multi-widget-input"> <div class="object-widget required"> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-listOfObject-0-widgets-foofield" name="form.widgets.listOfObject.0.widgets.foofield" type="text" value="99"> </div> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-barfield" name="form.widgets.listOfObject.0.widgets.barfield" type="text" value="bad"> </div> <input name="form.widgets.listOfObject.0-empty-marker" type="hidden" value="1"> </div> </div> </div> </div> <div class="buttons"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-add" name="form.widgets.listOfObject.buttons.add" type="submit" value="Add"> <input class="submit-widget button-field" id="form-widgets-listOfObject-buttons-remove" name="form.widgets.listOfObject.buttons.remove" type="submit" value="Remove selected"> </div> </div> <input name="form.widgets.listOfObject.count" type="hidden" value="1"> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> The object values must stay at the old ones: >>> root['first'].listOfObject[0].foofield 666 >>> root['first'].listOfObject[0].barfield 999 Simple but often used use-case is the display form: >>> editform = MyEditForm(root['first'], TestRequest()) >>> addTemplate(editform) >>> editform.mode = interfaces.DISPLAY_MODE >>> editform.update() >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-listOfObject">My list field</label> <div class="multi-widget" id="form-widgets-listOfObject"> <div class="row" id="form-widgets-listOfObject-0-row"> <div class="label"> <label for="form-widgets-listOfObject-0"> <span>my object widget</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-display"> <div class="object-widget"> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <span class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-foofield">666</span> </div> <div class="label"> <label for="form-widgets-listOfObject-0-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <span class="text-widget int-field" id="form-widgets-listOfObject-0-widgets-barfield">999</span> </div> </div> </div> </div> </div> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <span class="text-widget textline-field" id="form-widgets-name">first</span> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/objectmulti.rst
objectmulti.rst
=============== Browser support =============== The ``z3c.form`` library provides a form framework and widgets. This document ensures that we implement a widget for each field defined in ``zope.schema``. Take a look at the different widget doctest files for more information about the widgets. >>> import zope.schema >>> from z3c.form import browser Let's setup all required adapters using zcml. This makes sure we test the real configuration. >>> from zope.configuration import xmlconfig >>> import zope.component >>> import zope.security >>> import zope.i18n >>> import zope.browserresource >>> import z3c.form >>> xmlconfig.XMLConfig('meta.zcml', zope.component)() >>> xmlconfig.XMLConfig('meta.zcml', zope.security)() >>> xmlconfig.XMLConfig('meta.zcml', zope.i18n)() >>> xmlconfig.XMLConfig('meta.zcml', zope.browserresource)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.form)() >>> xmlconfig.XMLConfig('configure.zcml', z3c.form)() This utility is setup by hand, since its ZCML loads to many unwanted files: >>> import zope.component >>> import zope.i18n.negotiator >>> zope.component.provideUtility(zope.i18n.negotiator.negotiator) also define a helper method for test the widgets: >>> from z3c.form import interfaces >>> from z3c.form.testing import TestRequest >>> def setupWidget(field): ... request = TestRequest() ... widget = zope.component.getMultiAdapter((field, request), ... interfaces.IFieldWidget) ... widget.id = 'foo' ... widget.name = 'bar' ... return widget ASCII ----- >>> field = zope.schema.ASCII(default='This is\n ASCII.') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.textarea.TextAreaWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from ASCII to TextAreaWidget> >>> print(widget.render()) <textarea id="foo" name="bar" class="textarea-widget required ascii-field">This is ASCII.</textarea> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="textarea-widget required ascii-field">This is ASCII.</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="textarea-widget required ascii-field">This is ASCII.</span> </div> </div> As you can see, we will get an additional error class called ``row-error`` if we render a widget with an error view assinged: >>> class DummyErrorView(object): ... def render(self): ... return 'Dummy Error' >>> widget.error = (DummyErrorView()) >>> print(widget()) <div id="foo-row" class="row-error row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="textarea-widget required ascii-field">This is ASCII.</span> </div> <div class="error"> Dummy Error </div> </div> ASCIILine --------- >>> field = zope.schema.ASCIILine(default='An ASCII line.') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from ASCIILine to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required asciiline-field" value="An ASCII line." /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required asciiline-field">An ASCII line.</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required asciiline-field">An ASCII line.</span> </div> </div> Bool ---- >>> field = zope.schema.Bool(default=True, title=u"Check me", required=True) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.radio.RadioWidget'> >>> interfaces.IDataConverter(widget) <SequenceDataConverter converts from Bool to RadioWidget> >>> print(widget.render()) <span class="option"> <label for="foo-0"> <input type="radio" id="foo-0" name="bar" class="radio-widget required bool-field" value="true" checked="checked" /> <span class="label">yes</span> </label> </span><span class="option"> <label for="foo-1"> <input type="radio" id="foo-1" name="bar" class="radio-widget required bool-field" value="false" /> <span class="label">no</span> </label> </span> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="radio-widget required bool-field"><span class="selected-option">yes</span></span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span>Check me</span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="radio-widget required bool-field"><span class="selected-option">yes</span></span> </div> </div> For the boolean, the checkbox widget can be used as well: >>> from z3c.form.browser import checkbox >>> widget = checkbox.CheckBoxFieldWidget(field, TestRequest()) >>> widget.id = 'foo' >>> widget.name = 'bar' >>> widget.update() >>> print(widget.render()) <span id="foo"> <span class="option"> <input type="checkbox" id="foo-0" name="bar:list" class="checkbox-widget required bool-field" value="true" checked="checked" /> <label for="foo-0"> <span class="label">yes</span> </label> </span><span class="option"> <input type="checkbox" id="foo-1" name="bar:list" class="checkbox-widget required bool-field" value="false" /> <label for="foo-1"> <span class="label">no</span> </label> </span> </span> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="checkbox-widget required bool-field"><span class="selected-option">yes</span></span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span>Check me</span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="checkbox-widget required bool-field"><span class="selected-option">yes</span></span> </div> </div> We can also have a single checkbox button for the boolean. >>> widget = checkbox.SingleCheckBoxFieldWidget(field, TestRequest()) >>> widget.id = 'foo' >>> widget.name = 'bar' >>> widget.update() >>> print(widget.render()) <span class="option" id="foo"> <input type="checkbox" id="foo-0" name="bar:list" class="single-checkbox-widget required bool-field" value="selected" checked="checked" /> <label for="foo-0"> <span class="label">Check me</span> </label> </span> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="single-checkbox-widget required bool-field"><span class="selected-option">Check me</span></span> Note that the widget label is not repeated twice: >>> widget.label '' Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="single-checkbox-widget required bool-field"><span class="selected-option">Check me</span></span> </div> </div> Button ------ >>> from z3c.form import button >>> field = button.Button(title='Press me!') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.submit.SubmitWidget'> >>> print(widget.render()) <input type="submit" id="foo" name="bar" class="submit-widget button-field" value="Press me!" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <input type="submit" id="foo" name="bar" class="submit-widget button-field" value="Press me!" disabled="disabled" /> There exists an alternative widget for the button field, the button widget. It is not used by default, but available for use: >>> from z3c.form.browser.button import ButtonFieldWidget >>> widget = ButtonFieldWidget(field, TestRequest()) >>> widget.id = "foo" >>> widget.name = "bar" >>> widget.update() >>> print(widget.render()) <input type="button" id="foo" name="bar" class="button-widget button-field" value="Press me!" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <input type="button" id="foo" name="bar" class="button-widget button-field" value="Press me!" disabled="disabled" /> Bytes ----- >>> field = zope.schema.Bytes(default=b'Default bytes') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.file.FileWidget'> >>> interfaces.IDataConverter(widget) <FileUploadDataConverter converts from Bytes to FileWidget> >>> print(widget.render()) <input type="file" id="foo" name="bar" class="file-widget required bytes-field" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> widget.render().strip('\r\n') '<span id="foo" class="file-widget required bytes-field"></span>' Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="file-widget required bytes-field"></span> </div> </div> BytesLine --------- >>> field = zope.schema.BytesLine(default=b'A Bytes line.') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from BytesLine to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required bytesline-field" value="A Bytes line." /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required bytesline-field">A Bytes line.</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required bytesline-field">A Bytes line.</span> </div> </div> Choice ------ >>> from zope.schema import vocabulary >>> terms = [vocabulary.SimpleTerm(*value) for value in ... [(True, 'yes', 'Yes'), (False, 'no', 'No')]] >>> vocabulary = vocabulary.SimpleVocabulary(terms) >>> field = zope.schema.Choice(default=True, vocabulary=vocabulary) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.select.SelectWidget'> >>> interfaces.IDataConverter(widget) <SequenceDataConverter converts from Choice to SelectWidget> >>> print(widget.render()) <select id="foo" name="bar:list" class="select-widget required choice-field" size="1"> <option id="foo-0" value="yes" selected="selected">Yes</option> <option id="foo-1" value="no">No</option> </select> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="select-widget required choice-field"><span class="selected-option">Yes</span></span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="select-widget required choice-field"><span class="selected-option">Yes</span></span> </div> </div> Date ---- >>> import datetime >>> field = zope.schema.Date(default=datetime.date(2007, 4, 1)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <DateDataConverter converts from Date to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required date-field" value="07/04/01" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required date-field">07/04/01</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required date-field">07/04/01</span> </div> </div> Datetime -------- >>> field = zope.schema.Datetime(default=datetime.datetime(2007, 4, 1, 12)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <DatetimeDataConverter converts from Datetime to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required datetime-field" value="07/04/01 12:00" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required datetime-field">07/04/01 12:00</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required datetime-field">07/04/01 12:00</span> </div> </div> Decimal ------- >>> import decimal >>> field = zope.schema.Decimal(default=decimal.Decimal('1265.87')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <DecimalDataConverter converts from Decimal to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required decimal-field" value="1,265.87" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required decimal-field">1,265.87</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required decimal-field">1,265.87</span> </div> </div> Dict ---- There is no default widget for this field, since the sematics are fairly complex. DottedName ---------- >>> field = zope.schema.DottedName(default='z3c.form') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from DottedName to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required dottedname-field" value="z3c.form" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required dottedname-field">z3c.form</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required dottedname-field">z3c.form</span> </div> </div> Float ----- >>> field = zope.schema.Float(default=1265.8) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FloatDataConverter converts from Float to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required float-field" value="1,265.8" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required float-field">1,265.8</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required float-field">1,265.8</span> </div> </div> FrozenSet --------- >>> field = zope.schema.FrozenSet( ... value_type=zope.schema.Choice(values=(1, 2, 3, 4)), ... default=frozenset([1, 3]) ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.select.SelectWidget'> >>> interfaces.IDataConverter(widget) <CollectionSequenceDataConverter converts from FrozenSet to SelectWidget> >>> print(widget.render()) <select id="foo" name="bar:list" class="select-widget required frozenset-field" multiple="multiple" size="5"> <option id="foo-0" value="1" selected="selected">1</option> <option id="foo-1" value="2">2</option> <option id="foo-2" value="3" selected="selected">3</option> <option id="foo-3" value="4">4</option> </select> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="select-widget required frozenset-field"><span class="selected-option">1</span>, <span class="selected-option">3</span></span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="select-widget required frozenset-field"><span class="selected-option">1</span>, <span class="selected-option">3</span></span> </div> </div> Id -- >>> field = zope.schema.Id(default='z3c.form') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from Id to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required id-field" value="z3c.form" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required id-field">z3c.form</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required id-field">z3c.form</span> </div> </div> ImageButton ----------- Let's say we have a simple image field that uses the ``pressme.png`` image. >>> from z3c.form import button >>> field = button.ImageButton( ... image='pressme.png', ... title='Press me!') When the widget is created, the system converts the relative image path to an absolute image path by looking up the resource. For this to work, we have to setup some of the traversing machinery: # Traversing setup >>> from zope.traversing import testing >>> testing.setUp() # Resource namespace >>> import zope.component >>> from zope.traversing.interfaces import ITraversable >>> from zope.traversing.namespace import resource >>> zope.component.provideAdapter( ... resource, (None,), ITraversable, name="resource") >>> zope.component.provideAdapter( ... resource, (None, None), ITraversable, name="resource") # New absolute URL adapter for resources, if available >>> from zope.browserresource.resource import AbsoluteURL >>> zope.component.provideAdapter(AbsoluteURL) # Register the "pressme.png" resource >>> from zope.browserresource.resource import Resource >>> testing.browserResource('pressme.png', Resource) Now we are ready to instantiate the widget: >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.image.ImageWidget'> >>> print(widget.render()) <input type="image" id="foo" name="bar" class="image-widget imagebutton-field" src="http://127.0.0.1/@@/pressme.png" value="Press me!" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <input type="image" id="foo" name="bar" class="image-widget imagebutton-field" src="http://127.0.0.1/@@/pressme.png" value="Press me!" disabled="disabled" /> Int --- >>> field = zope.schema.Int(default=1200) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <IntegerDataConverter converts from Int to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required int-field" value="1,200" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required int-field">1,200</span> List - ASCII ------------ >>> field = zope.schema.List( ... value_type=zope.schema.ASCII( ... title='ASCII', ... default='This is\n ASCII.'), ... default=['foo\nfoo', 'bar\nbar']) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>ASCII</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required ascii-field">foo foo</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>ASCII</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required ascii-field">bar bar</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - ASCIILine ---------------- >>> field = zope.schema.List( ... value_type=zope.schema.ASCIILine( ... title='ASCIILine', ... default='An ASCII line.'), ... default=['foo', 'bar']) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>ASCIILine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required asciiline-field" value="foo" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>ASCIILine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required asciiline-field" value="bar" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Choice ------------- >>> field = zope.schema.List( ... value_type=zope.schema.Choice(values=(1, 2, 3, 4)), ... default=[1, 3] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.orderedselect.OrderedSelectWidget'> >>> interfaces.IDataConverter(widget) <CollectionSequenceDataConverter converts from List to OrderedSelectWidget> >>> print(widget.render()) <script src="++resource++orderedselect_input.js" type="text/javascript"></script> <table border="0" class="ordered-selection-field" id="foo"> <tr> <td> <select id="foo-from" name="bar.from" size="5" multiple="multiple" class="required list-field"> <option value="2">2</option> <option value="4">4</option> </select> </td> <td> <button name="from2toButton" type="button" value="&rarr;" onclick="javascript:from2to('foo')">&rarr;</button> <br /> <button name="to2fromButton" type="button" value="&larr;" onclick="javascript:to2from('foo')">&larr;</button> </td> <td> <select id="foo-to" name="bar.to" size="5" multiple="multiple" class="required list-field"> <option value="1">1</option> <option value="3">3</option> </select> <input name="bar-empty-marker" type="hidden" /> <span id="foo-toDataContainer" style="display: none"> <script type="text/javascript"> copyDataForSubmit('foo');</script> </span> </td> <td> <button name="upButton" type="button" value="&uarr;" onclick="javascript:moveUp('foo')">&uarr;</button> <br /> <button name="downButton" type="button" value="&darr;" onclick="javascript:moveDown('foo')">&darr;</button> </td> </tr> </table> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="required list-field"><span class="selected-option">1</span>, <span class="selected-option">3</span></span> List - Date ----------- >>> field = zope.schema.List( ... value_type=zope.schema.Date( ... title='Date', ... default=datetime.date(2007, 4, 1)), ... default=[datetime.date(2008, 9, 27), datetime.date(2008, 9, 28)]) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Date</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required date-field" value="08/09/27" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Date</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required date-field" value="08/09/28" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Datetime --------------- >>> field = zope.schema.List( ... value_type=zope.schema.Datetime( ... title='Datetime', ... default=datetime.datetime(2007, 4, 1, 12)), ... default=[datetime.datetime(2008, 9, 27, 12), ... datetime.datetime(2008, 9, 28, 12)]) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Datetime</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required datetime-field" value="08/09/27 12:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Datetime</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required datetime-field" value="08/09/28 12:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Decimal --------------- >>> field = zope.schema.List( ... value_type=zope.schema.Decimal( ... title='Decimal', ... default=decimal.Decimal('1265.87')), ... default=[decimal.Decimal('123.456'), decimal.Decimal('1')]) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Decimal</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required decimal-field" value="123.456" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Decimal</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required decimal-field" value="1" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - DottedName ----------------- >>> field = zope.schema.List( ... value_type=zope.schema.DottedName( ... title='DottedName', ... default='z3c.form'), ... default=['z3c.form', 'z3c.wizard']) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>DottedName</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required dottedname-field" value="z3c.form" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>DottedName</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required dottedname-field" value="z3c.wizard" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Float ------------ >>> field = zope.schema.List( ... value_type=zope.schema.Float( ... title='Float', ... default=123.456), ... default=[1234.5, 1]) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Float</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required float-field" value="1,234.5" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Float</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required float-field" value="1.0" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Id --------- >>> field = zope.schema.List( ... value_type=zope.schema.Id( ... title='Id', ... default='z3c.form'), ... default=['z3c.form', 'z3c.wizard']) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Id</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required id-field" value="z3c.form" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Id</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required id-field" value="z3c.wizard" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Int ---------- >>> field = zope.schema.List( ... value_type=zope.schema.Int( ... title='Int', ... default=666), ... default=[42, 43]) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Int</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Int</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Password --------------- >>> field = zope.schema.List( ... value_type=zope.schema.Password( ... title='Password', ... default='mypwd'), ... default=['pwd', 'pass']) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Password</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="password" id="foo-0" name="bar.0" class="password-widget required password-field" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Password</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="password" id="foo-1" name="bar.1" class="password-widget required password-field" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - SourceText ----------------- >>> field = zope.schema.List( ... value_type=zope.schema.SourceText( ... title='SourceText', ... default='<source />'), ... default=['<html></body>foo</body></html>', '<h1>bar</h1>'] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>SourceText</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required sourcetext-field">&lt;html&gt;&lt;/body&gt;foo&lt;/body&gt;&lt;/html&gt;</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>SourceText</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required sourcetext-field">&lt;h1&gt;bar&lt;/h1&gt;</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Text ----------- >>> field = zope.schema.List( ... value_type=zope.schema.Text( ... title='Text', ... default='Some\n Text.'), ... default=['foo\nfoo', 'bar\nbar'] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Text</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required text-field">foo foo</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Text</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required text-field">bar bar</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - TextLine --------------- >>> field = zope.schema.List( ... value_type=zope.schema.TextLine( ... title='TextLine', ... default='Some Text line.'), ... default=['foo', 'bar'] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>TextLine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required textline-field" value="foo" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>TextLine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required textline-field" value="bar" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Time ----------- >>> field = zope.schema.List( ... value_type=zope.schema.Time( ... title='Time', ... default=datetime.time(12, 0)), ... default=[datetime.time(13, 0), datetime.time(14, 0)] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Time</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required time-field" value="13:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Time</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required time-field" value="14:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - Timedelta ---------------- >>> field = zope.schema.List( ... value_type=zope.schema.Timedelta( ... title='Timedelta', ... default=datetime.timedelta(days=3)), ... default=[datetime.timedelta(days=4), datetime.timedelta(days=5)] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Timedelta</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required timedelta-field" value="4 days, 0:00:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Timedelta</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required timedelta-field" value="5 days, 0:00:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> List - URI ---------- >>> field = zope.schema.List( ... value_type=zope.schema.URI( ... title='URI', ... default='http://zope.org'), ... default=['http://www.python.org', 'http://www.zope.com'] ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from List to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>URI</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required uri-field" value="http://www.python.org" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>URI</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required uri-field" value="http://www.zope.com" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Object ------ By default, we are not going to provide widgets for an object, since we believe this is better done using sub-forms. Password -------- >>> field = zope.schema.Password(default='mypwd') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.password.PasswordWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from Password to PasswordWidget> >>> print(widget.render()) <input type="password" id="foo" name="bar" class="password-widget required password-field" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="password-widget required password-field">mypwd</span> Set --- >>> field = zope.schema.Set( ... value_type=zope.schema.Choice(values=(1, 2, 3, 4)), ... default=set([1, 3]) ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.select.SelectWidget'> >>> interfaces.IDataConverter(widget) <CollectionSequenceDataConverter converts from Set to SelectWidget> >>> print(widget.render()) <select id="foo" name="bar:list" class="select-widget required set-field" multiple="multiple" size="5"> <option id="foo-0" value="1" selected="selected">1</option> <option id="foo-1" value="2">2</option> <option id="foo-2" value="3" selected="selected">3</option> <option id="foo-3" value="4">4</option> </select> <input name="bar-empty-marker" type="hidden" value="1" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="select-widget required set-field"><span class="selected-option">1</span>, <span class="selected-option">3</span></span> SourceText ---------- >>> field = zope.schema.SourceText(default='<source />') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.textarea.TextAreaWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from SourceText to TextAreaWidget> >>> print(widget.render()) <textarea id="foo" name="bar" class="textarea-widget required sourcetext-field">&lt;source /&gt;</textarea> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="textarea-widget required sourcetext-field">&lt;source /&gt;</span> Text ---- >>> field = zope.schema.Text(default='Some\n Text.') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.textarea.TextAreaWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from Text to TextAreaWidget> >>> print(widget.render()) <textarea id="foo" name="bar" class="textarea-widget required text-field">Some Text.</textarea> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="textarea-widget required text-field">Some Text.</span> TextLine -------- >>> field = zope.schema.TextLine(default='Some Text line.') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from TextLine to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required textline-field" value="Some Text line." /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required textline-field">Some Text line.</span> Time ---- >>> field = zope.schema.Time(default=datetime.time(12, 0)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <TimeDataConverter converts from Time to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required time-field" value="12:00" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required time-field">12:00</span> Timedelta --------- >>> field = zope.schema.Timedelta(default=datetime.timedelta(days=3)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <TimedeltaDataConverter converts from Timedelta to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required timedelta-field" value="3 days, 0:00:00" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required timedelta-field">3 days, 0:00:00</span> Tuple - ASCII ------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.ASCII( ... title='ASCII', ... default='This is\n ASCII.'), ... default=('foo\nfoo', 'bar\nbar')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>ASCII</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required ascii-field">foo foo</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>ASCII</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required ascii-field">bar bar</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - ASCIILine ----------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.ASCIILine( ... title='ASCIILine', ... default='An ASCII line.'), ... default=('foo', 'bar')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>ASCIILine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required asciiline-field" value="foo" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>ASCIILine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required asciiline-field" value="bar" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Choice -------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Choice(values=(1, 2, 3, 4)), ... default=(1, 3) ) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.orderedselect.OrderedSelectWidget'> >>> interfaces.IDataConverter(widget) <CollectionSequenceDataConverter converts from Tuple to OrderedSelectWidget> >>> print(widget.render()) <script src="++resource++orderedselect_input.js" type="text/javascript"></script> <table border="0" class="ordered-selection-field" id="foo"> <tr> <td> <select id="foo-from" name="bar.from" size="5" multiple="multiple" class="required tuple-field"> <option value="2">2</option> <option value="4">4</option> </select> </td> <td> <button name="from2toButton" type="button" value="&rarr;" onclick="javascript:from2to('foo')">&rarr;</button> <br /> <button name="to2fromButton" type="button" value="&larr;" onclick="javascript:to2from('foo')">&larr;</button> </td> <td> <select id="foo-to" name="bar.to" size="5" multiple="multiple" class="required tuple-field"> <option value="1">1</option> <option value="3">3</option> </select> <input name="bar-empty-marker" type="hidden" /> <span id="foo-toDataContainer" style="display: none"> <script type="text/javascript"> copyDataForSubmit('foo');</script> </span> </td> <td> <button name="upButton" type="button" value="&uarr;" onclick="javascript:moveUp('foo')">&uarr;</button> <br /> <button name="downButton" type="button" value="&darr;" onclick="javascript:moveDown('foo')">&darr;</button> </td> </tr> </table> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="required tuple-field"><span class="selected-option">1</span>, <span class="selected-option">3</span></span> Tuple - Date ------------ >>> field = zope.schema.Tuple( ... value_type=zope.schema.Date( ... title='Date', ... default=datetime.date(2007, 4, 1)), ... default=(datetime.date(2008, 9, 27), datetime.date(2008, 9, 28))) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Date</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required date-field" value="08/09/27" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Date</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required date-field" value="08/09/28" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Datetime ---------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Datetime( ... title='Datetime', ... default=datetime.datetime(2007, 4, 1, 12)), ... default=(datetime.datetime(2008, 9, 27, 12), ... datetime.datetime(2008, 9, 28, 12))) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Datetime</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required datetime-field" value="08/09/27 12:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Datetime</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required datetime-field" value="08/09/28 12:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Decimal ---------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Decimal( ... title='Decimal', ... default=decimal.Decimal('1265.87')), ... default=(decimal.Decimal('123.456'), decimal.Decimal('1'))) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Decimal</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required decimal-field" value="123.456" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Decimal</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required decimal-field" value="1" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - DottedName ------------------ >>> field = zope.schema.Tuple( ... value_type=zope.schema.DottedName( ... title='DottedName', ... default='z3c.form'), ... default=('z3c.form', 'z3c.wizard')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>DottedName</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required dottedname-field" value="z3c.form" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>DottedName</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required dottedname-field" value="z3c.wizard" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Float ------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Float( ... title='Float', ... default=123.456), ... default=(1234.5, 1)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Float</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required float-field" value="1,234.5" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Float</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required float-field" value="1.0" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Id ---------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Id( ... title='Id', ... default='z3c.form'), ... default=('z3c.form', 'z3c.wizard')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Id</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required id-field" value="z3c.form" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Id</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required id-field" value="z3c.wizard" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Int ----------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Int( ... title='Int', ... default=666), ... default=(42, 43)) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Int</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required int-field" value="42" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Int</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required int-field" value="43" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Password ---------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Password( ... title='Password', ... default='mypwd'), ... default=('pwd', 'pass')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Password</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="password" id="foo-0" name="bar.0" class="password-widget required password-field" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Password</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="password" id="foo-1" name="bar.1" class="password-widget required password-field" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - SourceText ------------------ >>> field = zope.schema.Tuple( ... value_type=zope.schema.SourceText( ... title='SourceText', ... default='<source />'), ... default=('<html></body>foo</body></html>', '<h1>bar</h1>')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>SourceText</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required sourcetext-field">&lt;html&gt;&lt;/body&gt;foo&lt;/body&gt;&lt;/html&gt;</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>SourceText</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required sourcetext-field">&lt;h1&gt;bar&lt;/h1&gt;</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Text ------------ >>> field = zope.schema.Tuple( ... value_type=zope.schema.Text( ... title='Text', ... default='Some\n Text.'), ... default=('foo\nfoo', 'bar\nbar')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Text</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-0" name="bar.0" class="textarea-widget required text-field">foo foo</textarea> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Text</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><textarea id="foo-1" name="bar.1" class="textarea-widget required text-field">bar bar</textarea> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - TextLine ---------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.TextLine( ... title='TextLine', ... default='Some Text line.'), ... default=('foo', 'bar')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>TextLine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required textline-field" value="foo" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>TextLine</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required textline-field" value="bar" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Time ------------ >>> field = zope.schema.Tuple( ... value_type=zope.schema.Time( ... title='Time', ... default=datetime.time(12, 0)), ... default=(datetime.time(13, 0), datetime.time(14, 0))) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Time</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required time-field" value="13:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Time</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required time-field" value="14:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - Timedelta ----------------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.Timedelta( ... title='Timedelta', ... default=datetime.timedelta(days=3)), ... default=(datetime.timedelta(days=4), datetime.timedelta(days=5))) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>Timedelta</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required timedelta-field" value="4 days, 0:00:00" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>Timedelta</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required timedelta-field" value="5 days, 0:00:00" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> Tuple - URI ----------- >>> field = zope.schema.Tuple( ... value_type=zope.schema.URI( ... title='URI', ... default='http://zope.org'), ... default=('http://www.python.org', 'http://www.zope.com')) >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.multi.MultiWidget'> >>> interfaces.IDataConverter(widget) <MultiConverter converts from Tuple to MultiWidget> >>> print(widget.render()) <div class="multi-widget required"> <div id="foo-0-row" class="row"> <div class="label"> <label for="foo-0"> <span>URI</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-0-remove" name="bar.0.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-0" name="bar.0" class="text-widget required uri-field" value="http://www.python.org" /> </div> </div> </div> <div id="foo-1-row" class="row"> <div class="label"> <label for="foo-1"> <span>URI</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="multi-widget-checkbox"> <input type="checkbox" value="1" class="multi-widget-checkbox checkbox-widget" id="foo-1-remove" name="bar.1.remove" /> </div> <div class="multi-widget-input"><input type="text" id="foo-1" name="bar.1" class="text-widget required uri-field" value="http://www.zope.com" /> </div> </div> </div> <div class="buttons"> <input type="submit" id="bar-buttons-add" name="bar.buttons.add" class="submit-widget button-field" value="Add" /> <input type="submit" id="bar-buttons-remove" name="bar.buttons.remove" class="submit-widget button-field" value="Remove selected" /> </div> </div> <input type="hidden" name="bar.count" value="2" /> URI --- >>> field = zope.schema.URI(default='http://zope.org') >>> widget = setupWidget(field) >>> widget.update() >>> widget.__class__ <class 'z3c.form.browser.text.TextWidget'> >>> interfaces.IDataConverter(widget) <FieldDataConverter converts from URI to TextWidget> >>> print(widget.render()) <input type="text" id="foo" name="bar" class="text-widget required uri-field" value="http://zope.org" /> >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="foo" class="text-widget required uri-field">http://zope.org</span> Calling the widget will return the widget including the layout >>> print(widget()) <div id="foo-row" class="row-required row"> <div class="label"> <label for="foo"> <span></span> <span class="required">*</span> </label> </div> <div class="widget"> <span id="foo" class="text-widget required uri-field">http://zope.org</span> </div> </div>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/README.rst
README.rst
MultiWidget List integration tests ---------------------------------- Checking components on the highest possible level. >>> from datetime import date >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import testing >>> request = testing.TestRequest() >>> class EForm(form.EditForm): ... form.extends(form.EditForm) ... fields = field.Fields( ... testing.IMultiWidgetListIntegration).omit( ... 'listOfChoice', 'listOfObject') Our single content object: >>> obj = testing.MultiWidgetListIntegration() We recreate the form each time, to stay as close as possible. In real life the form gets instantiated and destroyed with each request. >>> def getForm(request, fname=None): ... frm = EForm(obj, request) ... testing.addTemplate(frm, 'integration_edit.pt') ... frm.update() ... content = frm.render() ... if fname is not None: ... testing.saveHtml(content, fname) ... return content Empty ##### All blank and empty values: >>> content = getForm(request, 'MultiWidget_list_edit_empty.html') >>> print(testing.plainText(content)) ListOfInt label <BLANKLINE> [Add] ListOfBool label <BLANKLINE> [Add] ListOfTextLine label <BLANKLINE> [Add] ListOfDate label <BLANKLINE> [Add] [Apply] Some valid default values ######################### >>> obj.listOfInt = [-100, 1, 100] >>> obj.listOfBool = [True, False, True] >>> obj.listOfChoice = ['two', 'three'] >>> obj.listOfTextLine = ['some text one', 'some txt two'] >>> obj.listOfDate = [date(2014, 6, 20)] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> >>> content = getForm(request, 'MultiWidget_list_edit_simple.html') >>> print(testing.plainText(content)) ListOfInt label <BLANKLINE> Int label * [ ] [-100] Int label * [ ] [1] Int label * [ ] [100] [Add] [Remove selected] ListOfBool label <BLANKLINE> Bool label * [ ] (O) yes ( ) no Bool label * [ ] ( ) yes (O) no Bool label * [ ] (O) yes ( ) no [Add] [Remove selected] ListOfTextLine label <BLANKLINE> TextLine label * [ ] [some text one] TextLine label * [ ] [some txt two] [Add] [Remove selected] ListOfDate label <BLANKLINE> Date label * [ ] [14/06/20] [Add] [Remove selected] [Apply] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> listOfInt ######### Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfInt.1'] = 'foobar' >>> submit['form.widgets.listOfInt.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The entered value is not a valid integer literal." for "foobar" and a new input. >>> content = getForm(request, 'MultiWidget_list_edit_submit_int.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfInt"]')) ListOfInt label <BLANKLINE> Int label * [ ] [-100] Int label * The entered value is not a valid integer literal. [ ] [foobar] Int label * [ ] [100] Int label * [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-listOfInt"]//div[@class="error"]')) The entered value is not a valid integer literal. Required input is missing. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfInt.1.remove'] = '1' >>> submit['form.widgets.listOfInt.2.remove'] = '1' >>> submit['form.widgets.listOfInt.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_list_edit_remove_int.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-listOfInt"]')) ListOfInt label <BLANKLINE> Int label * <BLANKLINE> [ ] [-100] Int label * <BLANKLINE> Required input is missing. [ ] [] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> listOfBool ########## Add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfBool.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get a new input. >>> content = getForm(request, 'MultiWidget_list_edit_submit_bool.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfBool"]')) ListOfBool label <BLANKLINE> Bool label * <BLANKLINE> [ ] (O) yes ( ) no Bool label * <BLANKLINE> [ ] ( ) yes (O) no Bool label * <BLANKLINE> [ ] (O) yes ( ) no Bool label * <BLANKLINE> [ ] ( ) yes ( ) no [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfBool"]//div[@class="error"]')) Required input is missing. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfBool.1.remove'] = '1' >>> submit['form.widgets.listOfBool.2.remove'] = '1' >>> submit['form.widgets.listOfBool.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_list_edit_remove_bool.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-listOfBool"]')) ListOfBool label <BLANKLINE> Bool label * <BLANKLINE> [ ] (O) yes ( ) no Bool label * <BLANKLINE> Required input is missing. [ ] ( ) yes ( ) no [Add] [Remove selected] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> listOfTextLine ############## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfTextLine.1'] = 'foo\nbar' >>> submit['form.widgets.listOfTextLine.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "Constraint not satisfied" for "foo\nbar" and a new input. >>> content = getForm(request, 'MultiWidget_list_edit_submit_textline.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfTextLine"]')) ListOfTextLine label <BLANKLINE> TextLine label * <BLANKLINE> [ ] [some text one] TextLine label * <BLANKLINE> Constraint not satisfied [ ] [foo bar] TextLine label * <BLANKLINE> [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfTextLine"]//div[@class="error"]')) Constraint not satisfied Required input is missing. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfTextLine.0.remove'] = '1' >>> submit['form.widgets.listOfTextLine.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_list_edit_remove_textline.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-listOfTextLine"]')) ListOfTextLine label <BLANKLINE> TextLine label * <BLANKLINE> Constraint not satisfied [ ] [foo bar] TextLine label * <BLANKLINE> Required input is missing. [ ] [] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> listOfDate ########## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfDate.0'] = 'foobar' >>> submit['form.widgets.listOfDate.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The datetime string did not match the pattern" for "foobar" and a new input. >>> content = getForm(request, 'MultiWidget_list_edit_submit_date.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfDate"]')) ListOfDate label <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] Date label * <BLANKLINE> [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfDate"]//div[@class="error"]')) The datetime string did not match the pattern 'yy/MM/dd'. Required input is missing. Add one more field: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfDate.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) And fill in a valid value: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfDate.2'] = '14/06/21' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_list_edit_submit_date2.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-listOfDate"]')) ListOfDate label <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] Date label * <BLANKLINE> Required input is missing. [ ] [] Date label * <BLANKLINE> [ ] [14/06/21] [Add] [Remove selected] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfDate.2.remove'] = '1' >>> submit['form.widgets.listOfDate.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_list_edit_remove_date.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-listOfDate"]')) ListOfDate label <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] Date label * <BLANKLINE> Required input is missing. [ ] [] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> And apply >>> submit = testing.getSubmitValues(content) >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) There were some errors. * ListOfInt label: Wrong contained type * ListOfBool label: Wrong contained type * ListOfTextLine label: Constraint not satisfied * ListOfDate label: The datetime string did not match the pattern 'yy/MM/dd'. ... >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False, True] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 20)] listOfInt: [-100, 1, 100] listOfTextLine: ['some text one', 'some txt two']> Let's fix the values >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.listOfInt.1'] = '42' >>> submit['form.widgets.listOfBool.1'] = 'false' >>> submit['form.widgets.listOfTextLine.0'] = 'ipsum lorem' >>> submit['form.widgets.listOfTextLine.1'] = 'lorem ipsum' >>> submit['form.widgets.listOfDate.0'] = '14/06/25' >>> submit['form.widgets.listOfDate.1'] = '14/06/24' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj) <MultiWidgetListIntegration listOfBool: [True, False] listOfChoice: ['two', 'three'] listOfDate: [datetime.date(2014, 6, 25), datetime.date(2014, 6, 24)] listOfInt: [-100, 42] listOfTextLine: ['ipsum lorem', 'lorem ipsum']>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/multi_list_integration.rst
multi_list_integration.rst
MultiWidget Dict integration tests ---------------------------------- Checking components on the highest possible level. >>> from datetime import date >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import testing >>> request = testing.TestRequest() >>> class EForm(form.EditForm): ... form.extends(form.EditForm) ... fields = field.Fields( ... testing.IMultiWidgetDictIntegration).omit('dictOfObject') Our single content object: >>> obj = testing.MultiWidgetDictIntegration() We recreate the form each time, to stay as close as possible. In real life the form gets instantiated and destroyed with each request. >>> def getForm(request, fname=None): ... frm = EForm(obj, request) ... testing.addTemplate(frm, 'integration_edit.pt') ... frm.update() ... content = frm.render() ... if fname is not None: ... testing.saveHtml(content, fname) ... return content Empty ##### All blank and empty values: >>> content = getForm(request, 'MultiWidget_dict_edit_empty.html') >>> print(testing.plainText(content)) DictOfInt label <BLANKLINE> [Add] DictOfBool label <BLANKLINE> [Add] DictOfChoice label <BLANKLINE> [Add] DictOfTextLine label <BLANKLINE> [Add] DictOfDate label <BLANKLINE> [Add] [Apply] Some valid default values ######################### >>> obj.dictOfInt = {-101: -100, -1:1, 101:100} >>> obj.dictOfBool = {True: False, False: True} >>> obj.dictOfChoice = {'key1': 'three', 'key3': 'two'} >>> obj.dictOfTextLine = {'textkey1': 'some text one', ... 'textkey2': 'some txt two'} >>> obj.dictOfDate = { ... date(2011, 1, 15): date(2014, 6, 20), ... date(2012, 2, 20): date(2013, 5, 19)} >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> >>> content = getForm(request, 'MultiWidget_dict_edit_simple.html') >>> print(testing.plainText(content)) DictOfInt label <BLANKLINE> Int key * [-1] Int label * [ ] [1] Int key * [-101] Int label * [ ] [-100] Int key * [101] Int label * [ ] [100] [Add] [Remove selected] DictOfBool label <BLANKLINE> Bool key * ( ) yes (O) no Bool label * [ ] (O) yes ( ) no Bool key * (O) yes ( ) no Bool label * [ ] ( ) yes (O) no [Add] [Remove selected] DictOfChoice label <BLANKLINE> Choice key * [key1] Choice label * [ ] [three] Choice key * [key3] Choice label * [ ] [two] [Add] [Remove selected] DictOfTextLine label <BLANKLINE> TextLine key * [textkey1] TextLine label * [ ] [some text one] TextLine key * [textkey2] TextLine label * [ ] [some txt two] [Add] [Remove selected] DictOfDate label <BLANKLINE> Date key * [11/01/15] Date label * [ ] [14/06/20] Date key * [12/02/20] Date label * [ ] [13/05/19] [Add] [Remove selected] [Apply] dictOfInt ######### Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfInt.key.2'] = 'foobar' >>> submit['form.widgets.dictOfInt.2'] = 'foobar' >>> submit['form.widgets.dictOfInt.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The entered value is not a valid integer literal." for "foobar" and a new input. >>> content = getForm(request, 'MultiWidget_dict_edit_submit_int.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfInt"]')) DictOfInt label <BLANKLINE> Int key * <BLANKLINE> [-1] <BLANKLINE> Int label * <BLANKLINE> [ ] [1] Int key * <BLANKLINE> [-101] <BLANKLINE> Int label * <BLANKLINE> [ ] [-100] Int key * <BLANKLINE> The entered value is not a valid integer literal. [foobar] <BLANKLINE> Int label * <BLANKLINE> The entered value is not a valid integer literal. [ ] [foobar] Int key * <BLANKLINE> [] <BLANKLINE> Int label * <BLANKLINE> [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_int2.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfInt"]//div[@class="error"]')) Required input is missing. Required input is missing. The entered value is not a valid integer literal. The entered value is not a valid integer literal. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfInt.1.remove'] = '1' >>> submit['form.widgets.dictOfInt.3.remove'] = '1' >>> submit['form.widgets.dictOfInt.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_remove_int.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfInt"]')) DictOfInt label <BLANKLINE> Int key * <BLANKLINE> Required input is missing. [] <BLANKLINE> Int label * <BLANKLINE> Required input is missing. [ ] [] Int key * <BLANKLINE> [-101] <BLANKLINE> Int label * <BLANKLINE> [ ] [-100] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> dictOfBool ########## Add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfBool.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get a new input. >>> content = getForm(request, 'MultiWidget_dict_edit_submit_bool.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfBool"]')) DictOfBool label <BLANKLINE> Bool key * <BLANKLINE> ( ) yes (O) no <BLANKLINE> Bool label * <BLANKLINE> [ ] (O) yes ( ) no Bool key * <BLANKLINE> (O) yes ( ) no <BLANKLINE> Bool label * <BLANKLINE> [ ] ( ) yes (O) no Bool key * <BLANKLINE> ( ) yes ( ) no <BLANKLINE> Bool label * <BLANKLINE> [ ] ( ) yes ( ) no [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_bool2.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfBool"]//div[@class="error"]')) Required input is missing. Required input is missing. Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfBool.1.remove'] = '1' >>> submit['form.widgets.dictOfBool.2.remove'] = '1' >>> submit['form.widgets.dictOfBool.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_remove_bool.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfBool"]')) DictOfBool label <BLANKLINE> Bool key * <BLANKLINE> Required input is missing. ( ) yes ( ) no <BLANKLINE> Bool label * <BLANKLINE> Required input is missing. [ ] ( ) yes ( ) no [Add] [Remove selected] >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> dictOfChoice ############ Add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfChoice.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get a new input. >>> content = getForm(request, 'MultiWidget_dict_edit_submit_choice.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfChoice"]')) DictOfChoice label <BLANKLINE> Choice key * <BLANKLINE> [key1] <BLANKLINE> Choice label * <BLANKLINE> [ ] [three] Choice key * <BLANKLINE> [key3] <BLANKLINE> Choice label * <BLANKLINE> [ ] [two] Choice key * <BLANKLINE> [[ ]] <BLANKLINE> Choice label * <BLANKLINE> [ ] [[ ]] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_choice2.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfChoice"]//div[@class="error"]')) Duplicate key Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfChoice.0.remove'] = '1' >>> submit['form.widgets.dictOfChoice.1.remove'] = '1' >>> submit['form.widgets.dictOfChoice.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_remove_choice.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfChoice"]')) DictOfChoice label <BLANKLINE> Choice key * <BLANKLINE> [key3] <BLANKLINE> Choice label * <BLANKLINE> [ ] [two] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> dictOfTextLine ############## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfTextLine.key.0'] = 'foo\nbar' >>> submit['form.widgets.dictOfTextLine.0'] = 'foo\nbar' >>> submit['form.widgets.dictOfTextLine.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "Constraint not satisfied" for "foo\nbar" and a new input. >>> content = getForm(request, 'MultiWidget_dict_edit_submit_textline.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfTextLine"]')) DictOfTextLine label <BLANKLINE> TextLine key * <BLANKLINE> Constraint not satisfied [foo bar] <BLANKLINE> TextLine label * <BLANKLINE> Constraint not satisfied [ ] [foo bar] TextLine key * <BLANKLINE> [textkey2] <BLANKLINE> TextLine label * <BLANKLINE> [ ] [some txt two] TextLine key * <BLANKLINE> [] <BLANKLINE> TextLine label * <BLANKLINE> [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_textline2.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfTextLine"]//div[@class="error"]')) Required input is missing. Required input is missing. Constraint not satisfied Constraint not satisfied Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfTextLine.2.remove'] = '1' >>> submit['form.widgets.dictOfTextLine.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_remove_textline.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfTextLine"]')) DictOfTextLine label <BLANKLINE> TextLine key * <BLANKLINE> Required input is missing. [] <BLANKLINE> TextLine label * <BLANKLINE> Required input is missing. [ ] [] TextLine key * <BLANKLINE> Constraint not satisfied [foo bar] <BLANKLINE> TextLine label * <BLANKLINE> Constraint not satisfied [ ] [foo bar] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> dictOfDate ########## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfDate.key.0'] = 'foobar' >>> submit['form.widgets.dictOfDate.0'] = 'foobar' >>> submit['form.widgets.dictOfDate.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The entered value is not a valid integer literal." for "foobar" and a new input. >>> content = getForm(request, 'MultiWidget_dict_edit_submit_date.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfDate"]')) DictOfDate label <BLANKLINE> Date key * <BLANKLINE> [12/02/20] <BLANKLINE> Date label * <BLANKLINE> [ ] [13/05/19] Date key * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [foobar] <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] Date key * <BLANKLINE> [] <BLANKLINE> Date label * <BLANKLINE> [ ] [] [Add] [Remove selected] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_date2.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfDate"]//div[@class="error"]')) Required input is missing. Required input is missing. The datetime string did not match the pattern 'yy/MM/dd'. The datetime string did not match the pattern 'yy/MM/dd'. And fill in a valid value: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfDate.key.0'] = '14/05/12' >>> submit['form.widgets.dictOfDate.0'] = '14/06/21' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_submit_date3.html') >>> print(testing.plainText(content, ... './/form/div[@id="row-form-widgets-dictOfDate"]')) DictOfDate label <BLANKLINE> Date key * <BLANKLINE> [12/02/20] <BLANKLINE> Date label * <BLANKLINE> [ ] [13/05/19] Date key * <BLANKLINE> [14/05/12] <BLANKLINE> Date label * <BLANKLINE> [ ] [14/06/21] Date key * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [foobar] <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] [Add] [Remove selected] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfDate.1.remove'] = '1' >>> submit['form.widgets.dictOfDate.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_remove_date.html') >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-dictOfDate"]')) DictOfDate label <BLANKLINE> Date key * <BLANKLINE> [12/02/20] <BLANKLINE> Date label * <BLANKLINE> [ ] [13/05/19] Date key * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [foobar] <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [ ] [foobar] [Add] [Remove selected] >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> And apply >>> submit = testing.getSubmitValues(content) >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) There were some errors. * DictOfInt label: Wrong contained type * DictOfBool label: Wrong contained type * DictOfTextLine label: Constraint not satisfied * DictOfDate label: The datetime string did not match the pattern 'yy/MM/dd'. ... >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True, True: False} dictOfChoice: {'key1': 'three', 'key3': 'two'} dictOfDate: {datetime.date(2011, 1, 15): datetime.date(2014, 6, 20), datetime.date(2012, 2, 20): datetime.date(2013, 5, 19)} dictOfInt: {-101: -100, -1: 1, 101: 100} dictOfTextLine: {'textkey1': 'some text one', 'textkey2': 'some txt two'}> Let's fix the values >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfInt.key.1'] = '42' >>> submit['form.widgets.dictOfInt.1'] = '43' >>> submit['form.widgets.dictOfTextLine.0.remove'] = '1' >>> submit['form.widgets.dictOfTextLine.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfTextLine.key.0'] = 'lorem ipsum' >>> submit['form.widgets.dictOfTextLine.0'] = 'ipsum lorem' >>> submit['form.widgets.dictOfDate.key.1'] = '14/06/25' >>> submit['form.widgets.dictOfDate.1'] = '14/07/28' >>> submit['form.widgets.dictOfInt.key.0'] = '-101' >>> submit['form.widgets.dictOfInt.0'] = '-100' >>> submit['form.widgets.dictOfBool.key.0'] = 'false' >>> submit['form.widgets.dictOfBool.0'] = 'true' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_fixit.html') >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: True} dictOfChoice: {'key3': 'two'} dictOfDate: {datetime.date(2012, 2, 20): datetime.date(2013, 5, 19), datetime.date(2014, 6, 25): datetime.date(2014, 7, 28)} dictOfInt: {-101: -100, 42: 43} dictOfTextLine: {'lorem ipsum': 'ipsum lorem'}> Twisting some keys ################## Change key values, item values must stick to the new values. >>> obj.dictOfInt = {-101: -100, -1:1, 101:100} >>> obj.dictOfBool = {True: False, False: True} >>> obj.dictOfChoice = {'key1': 'three', 'key3': 'two'} >>> obj.dictOfTextLine = {'textkey1': 'some text one', ... 'textkey2': 'some txt two'} >>> obj.dictOfDate = { ... date(2011, 1, 15): date(2014, 6, 20), ... date(2012, 2, 20): date(2013, 5, 19)} >>> request = testing.TestRequest() >>> content = getForm(request, 'MultiWidget_dict_edit_twist.html') >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfInt.key.2'] = '42' # was 101:100 >>> submit['form.widgets.dictOfBool.key.0'] = 'true' # was False:True >>> submit['form.widgets.dictOfBool.key.1'] = 'false' # was True:False >>> submit['form.widgets.dictOfChoice.key.1:list'] = 'key2' # was key3: two >>> submit['form.widgets.dictOfChoice.key.0:list'] = 'key3' # was key1: three >>> submit['form.widgets.dictOfTextLine.key.1'] = 'lorem' # was textkey2: some txt two >>> submit['form.widgets.dictOfTextLine.1'] = 'ipsum' # was textkey2: some txt two >>> submit['form.widgets.dictOfTextLine.key.0'] = 'foobar' # was textkey1: some txt one >>> submit['form.widgets.dictOfDate.key.0'] = '14/06/25' # 11/01/15: 14/06/20 >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'MultiWidget_dict_edit_twist2.html') >>> submit = testing.getSubmitValues(content) >>> pprint(obj) <MultiWidgetDictIntegration dictOfBool: {False: False, True: True} dictOfChoice: {'key2': 'two', 'key3': 'three'} dictOfDate: {datetime.date(2012, 2, 20): datetime.date(2013, 5, 19), datetime.date(2014, 6, 25): datetime.date(2014, 6, 20)} dictOfInt: {-101: -100, -1: 1, 42: 100} dictOfTextLine: {'foobar': 'some text one', 'lorem': 'ipsum'}>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/multi_dict_integration.rst
multi_dict_integration.rst
TextArea Widget --------------- The widget can render a text area field for a text: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import textarea The ``TextAreaWidget`` is a widget: >>> verifyClass(interfaces.IWidget, textarea.TextAreaWidget) True The widget can render a input field only by adapting a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = textarea.TextAreaWidget(request) Such a field provides IWidget: >>> interfaces.IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import z3c.form.browser >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'textarea_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML: >>> print(widget.render()) <textarea class="textarea-widget"></textarea> Adding some more attributes to the widget will make it display more: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'value' >>> print(widget.render()) <textarea id="id" name="name" class="textarea-widget">value</textarea> The json data representing the textarea widget: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'id', 'label': '', 'mode': 'input', 'name': 'name', 'required': False, 'type': 'textarea', 'value': 'value'} Check DISPLAY_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'textarea_display.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='display') >>> widget.value = u'foobar' >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="id" class="textarea-widget">foobar</span> Check HIDDEN_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'textarea_hidden.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden') >>> widget.value = u'foobar' >>> widget.mode = interfaces.HIDDEN_MODE >>> print(widget.render()) <input class="hidden-widget" id="id" name="name" type="hidden" value="foobar">
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/textarea.rst
textarea.rst
"""Browser Widget Framework Interfaces """ import zope.interface import zope.schema class IWidgetLayoutSupport(zope.interface.Interface): css = zope.schema.TextLine( title='Widget layout CSS class name(s)', description=('This attribute defines one or more layout class names.'), default='row', required=False) def getCSSClass(klass=None, error=None, required=None, classPattern='%(class)s', errorPattern='%(class)s-error', requiredPattern='%(class)s-required'): """Setup given css class (klass) with error and required postfix If no klass name is given the widget.wrapper class name/names get used. It is also possible if more then one (empty space separated) names are given as klass argument. This method can get used from your form or widget template or widget layout template without to re-implement the widget itself just because you a different CSS class concept. """ class IHTMLCoreAttributes(zope.interface.Interface): """The HTML element 'core' attributes.""" id = zope.schema.ASCIILine( title='Id', description=('This attribute assigns a name to an element. This ' 'name must be unique in a document.'), required=False) # HTML "class" attribute; "class" is a keyword in Python. klass = zope.schema.TextLine( title='Class', description=('This attribute assigns a class name or set of ' 'class names to an element. Any number of elements ' 'may be assigned the same class name or names.'), required=False) style = zope.schema.TextLine( title='Style', description=('This attribute offers advisory information about ' 'the element for which it is set.'), required=False) title = zope.schema.TextLine( title='Title', description=('This attribute offers advisory information about ' 'the element for which it is set.'), required=False) class IHTMLI18nAttributes(zope.interface.Interface): """The HTML element 'i18n' attributes.""" lang = zope.schema.TextLine( title='Language', description=("This attribute specifies the base language of an " "element's attribute values and text content."), required=False) class IHTMLEventsAttributes(zope.interface.Interface): """The HTML element 'events' attributes.""" onclick = zope.schema.TextLine( title='On Click', description=('The ``onclick`` event occurs when the pointing device ' 'button is clicked over an element.'), required=False) ondblclick = zope.schema.TextLine( title='On Double-Click', description=('The ``ondblclick`` event occurs when the pointing ' 'device button is double clicked over an element.'), required=False) onmousedown = zope.schema.TextLine( title='On Mouse Down', description=('The onmousedown event occurs when the pointing ' 'device button is pressed over an element.'), required=False) onmouseup = zope.schema.TextLine( title='On Mouse Up', description=('The ``onmouseup`` event occurs when the pointing ' 'device button is released over an element.'), required=False) onmouseover = zope.schema.TextLine( title='On Mouse Over', description=('The ``onmouseover`` event occurs when the pointing ' 'device is moved onto an element.'), required=False) onmousemove = zope.schema.TextLine( title='On Mouse Move', description=('The ``onmousemove`` event occurs when the pointing ' 'device is moved while it is over an element.'), required=False) onmouseout = zope.schema.TextLine( title='On Mouse Out', description=('The ``onmouseout`` event occurs when the pointing ' 'device is moved away from an element.'), required=False) onkeypress = zope.schema.TextLine( title='On Key Press', description=('The ``onkeypress`` event occurs when a key is ' 'pressed and released over an element.'), required=False) onkeydown = zope.schema.TextLine( title='On Key Down', description=('The ``onkeydown`` event occurs when a key is pressed ' 'down over an element.'), required=False) onkeyup = zope.schema.TextLine( title='On Key Up', description=('The ``onkeyup`` event occurs when a key is released ' 'over an element.'), required=False) class IHTMLFormElement(IHTMLCoreAttributes, IHTMLI18nAttributes, IHTMLEventsAttributes, IWidgetLayoutSupport): """A generic form-related element including layout template support.""" disabled = zope.schema.Choice( title='Disabled', description=('When set for a form control, this boolean attribute ' 'disables the control for user input.'), values=(None, 'disabled'), required=False) tabindex = zope.schema.Int( title='Tab Index', description=('This attribute specifies the position of the current ' 'element in the tabbing order for the current ' 'document. This value must be a number between 0 and ' '32767.'), required=False) onfocus = zope.schema.TextLine( title='On Focus', description=('The ``onfocus`` event occurs when an element receives ' 'focus either by the pointing device or by tabbing ' 'navigation.'), required=False) onblur = zope.schema.TextLine( title='On blur', description=('The ``onblur`` event occurs when an element loses ' 'focus either by the pointing device or by tabbing ' 'navigation.'), required=False) onchange = zope.schema.TextLine( title='On Change', description=('The onchange event occurs when a control loses the ' 'input focus and its value has been modified since ' 'gaining focus.'), required=False) def addClass(klass): """Add a class to the HTML element. The class must be added to the ``klass`` attribute. """ class IHTMLInputWidget(IHTMLFormElement): """A widget using the HTML INPUT element.""" readonly = zope.schema.Choice( title='Read-Only', description=('When set for a form control, this boolean attribute ' 'prohibits changes to the control.'), values=(None, 'readonly'), required=False) alt = zope.schema.TextLine( title='Alternate Text', description=('For user agents that cannot display images, forms, ' 'or applets, this attribute specifies alternate text.'), required=False) accesskey = zope.schema.TextLine( title='Access Key', description=('This attribute assigns an access key to an element.'), min_length=1, max_length=1, required=False) onselect = zope.schema.TextLine( title='On Select', description=('The ``onselect`` event occurs when a user selects ' 'some text in a text field.'), required=False) class IHTMLImageWidget(IHTMLInputWidget): """A widget using the HTML INPUT element with type 'image'.""" src = zope.schema.TextLine( title='Image Source', description=('The source of the image used to display the widget.'), required=True) class IHTMLTextInputWidget(IHTMLFormElement): """A widget using the HTML INPUT element (for text types).""" size = zope.schema.Int( title='Size', description=('This attribute tells the user agent the initial width ' 'of the control -- in this case in characters.'), required=False) maxlength = zope.schema.Int( title='Maximum Length', description=('This attribute specifies the maximum number of ' 'characters the user may enter.'), required=False) placeholder = zope.schema.TextLine( title='Placeholder Text', description=('This attribute represents a short hint ' '(a word or short phrase) intended to aid the user ' 'with data entry when the control has no value.'), required=False) autocapitalize = zope.schema.Choice( title='Auto-Capitalization Control', description=('This attribute controls whether the browser should ' 'automatically capitalize the input value.'), values=('off', 'on'), required=False) class IHTMLTextAreaWidget(IHTMLFormElement): """A widget using the HTML TEXTAREA element.""" rows = zope.schema.Int( title='Rows', description=('This attribute specifies the number of visible text ' 'lines.'), required=False) cols = zope.schema.Int( title='columns', description=('This attribute specifies the visible width in average ' 'character widths.'), required=False) readonly = zope.schema.Choice( title='Read-Only', description=('When set for a form control, this boolean attribute ' 'prohibits changes to the control.'), values=(None, 'readonly'), required=False) accesskey = zope.schema.TextLine( title='Access Key', description=('This attribute assigns an access key to an element.'), min_length=1, max_length=1, required=False) onselect = zope.schema.TextLine( title='On Select', description=('The ``onselect`` event occurs when a user selects ' 'some text in a text field.'), required=False) class IHTMLSelectWidget(IHTMLFormElement): """A widget using the HTML SELECT element.""" multiple = zope.schema.Choice( title='Multiple', description=('If set, this boolean attribute allows multiple ' 'selections.'), values=(None, 'multiple'), required=False) size = zope.schema.Int( title='Size', description=('If a SELECT element is presented as a scrolled ' 'list box, this attribute specifies the number of ' 'rows in the list that should be visible at the ' 'same time.'), default=1, required=False)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/interfaces.py
interfaces.py
Text Widget ----------- The widget can render a input field for a text line: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import text The TextWidget is a widget: >>> verifyClass(interfaces.IWidget, text.TextWidget) True The widget can render a input field only by adapting a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = text.TextWidget(request) Such a field provides IWidget: >>> interfaces.IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import z3c.form.browser >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'text_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML: >>> print(widget.render()) <input type="text" class="text-widget" value="" /> Adding some more attributes to the widget will make it display more: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'value' >>> widget.style = u'color: blue' >>> widget.placeholder = u'Email address' >>> widget.autocapitalize = u'off' >>> print(widget.render()) <input type="text" id="id" name="name" class="text-widget" placeholder="Email address" autocapitalize="off" style="color: blue" value="value" /> Check DISPLAY_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'text_display.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='display') >>> widget.value = u'foobar' >>> widget.style = None >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="id" class="text-widget">foobar</span> Check HIDDEN_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'text_hidden.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden') >>> widget.value = u'foobar' >>> widget.mode = interfaces.HIDDEN_MODE >>> print(widget.render()) <input id="id" name="name" value="foobar" class="hidden-widget" type="hidden" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/text.rst
text.rst
function moveItems(from, to) { // shortcuts for selection fields var src = document.getElementById(from); var tgt = document.getElementById(to); if (src.selectedIndex == -1) selectionError(); else { // iterate over all selected items // --> attribute "selectedIndex" doesn't support multiple selection. // Anyway, it works here, as a moved item isn't selected anymore, // thus "selectedIndex" indicating the "next" selected item :) while (src.selectedIndex > -1) if (src.options[src.selectedIndex].selected) { // create a new virtal object with values of item to copy temp = new Option(src.options[src.selectedIndex].text, src.options[src.selectedIndex].value); // append virtual object to targe tgt.options[tgt.length] = temp; // want to select newly created item temp.selected = true; // delete moved item in source src.options[src.selectedIndex] = null; } } } // move item from "from" selection to "to" selection function from2to(name) { moveItems(name+"-from", name+"-to"); copyDataForSubmit(name); } // move item from "to" selection back to "from" selection function to2from(name) { moveItems(name+"-to", name+"-from"); copyDataForSubmit(name); } function swapFields(a, b) { // swap text var temp = a.text; a.text = b.text; b.text = temp; // swap value temp = a.value; a.value = b.value; b.value = temp; // swap selection temp = a.selected; a.selected = b.selected; b.selected = temp; } // move selected item in "to" selection one up function moveUp(name) { // shortcuts for selection field var toSel = document.getElementById(name+"-to"); if (toSel.selectedIndex == -1) selectionError(); else for (var i = 1; i < toSel.length; i++) if (toSel.options[i].selected) { swapFields(toSel.options[i-1], toSel.options[i]); copyDataForSubmit(name); } } // move selected item in "to" selection one down function moveDown(name) { // shortcuts for selection field var toSel = document.getElementById(name+"-to"); if (toSel.selectedIndex == -1) { selectionError(); } else { for (var i = toSel.length-2; i >= 0; i--) { if (toSel.options[i].selected) { swapFields(toSel.options[i+1], toSel.options[i]); } } copyDataForSubmit(name); } } // copy each item of "toSel" into one hidden input field function copyDataForSubmit(name) { // shortcuts for selection field and hidden data field var toSel = document.getElementById(name+"-to"); var toDataContainer = document.getElementById(name+"-toDataContainer"); // delete all child nodes (--> complete content) of "toDataContainer" span while (toDataContainer.hasChildNodes()) toDataContainer.removeChild(toDataContainer.firstChild); // create new hidden input fields - one for each selection item of // "to" selection for (var i = 0; i < toSel.options.length; i++) { // create virtual node with suitable attributes var newNode = document.createElement("input"); newNode.setAttribute("name", name.replace(/-/g, '.')+':list'); newNode.setAttribute("type", "hidden"); newNode.setAttribute("value",toSel.options[i].value ); // actually append virtual node to DOM tree toDataContainer.appendChild(newNode); } } // error message for missing selection function selectionError() {alert("Must select something!")}
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/orderedselect_input.js
orderedselect_input.js
Select Widget ------------- The select widget allows you to select one or more values from a set of given options. The "SELECT" and "OPTION" elements are described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-SELECT As for all widgets, the select widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import select >>> verifyClass(interfaces.IWidget, select.SelectWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = select.SelectWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get an empty widget: >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's provide some values for this widget. We can do this by defining a source providing ``ITerms``. This source uses descriminators which will fit our setup. >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary >>> import z3c.form.term >>> class SelectionTerms(z3c.form.term.Terms): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary.fromValues(['a', 'b', 'c']) >>> zope.component.provideAdapter(SelectionTerms, ... (None, interfaces.IFormLayer, None, None, interfaces.ISelectWidget) ) Now let's try if we get widget values: >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" selected="selected" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="a">a</option> <option id="widget-id-1" value="b">b</option> <option id="widget-id-2" value="c">c</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Select json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'content': 'No value', 'id': 'widget-id-novalue', 'selected': True, 'value': '--NOVALUE--'}, {'content': 'a', 'id': 'widget-id-0', 'selected': False, 'value': 'a'}, {'content': 'b', 'id': 'widget-id-1', 'selected': False, 'value': 'b'}, {'content': 'c', 'id': 'widget-id-2', 'selected': False, 'value': 'c'}], 'required': False, 'type': 'select', 'value': ()} If we select item "b", then it should be selected: >>> widget.value = ['b'] >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="a">a</option> <option id="widget-id-1" value="b" selected="selected">b</option> <option id="widget-id-2" value="c">c</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Select json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'content': 'No value', 'id': 'widget-id-novalue', 'selected': False, 'value': '--NOVALUE--'}, {'content': 'a', 'id': 'widget-id-0', 'selected': False, 'value': 'a'}, {'content': 'b', 'id': 'widget-id-1', 'selected': True, 'value': 'b'}, {'content': 'c', 'id': 'widget-id-2', 'selected': False, 'value': 'c'}], 'required': False, 'type': 'select', 'value': ['b']} Let's see what happens if we have values that are not in the vocabulary: >>> widget.value = ['x', 'y'] >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="a">a</option> <option id="widget-id-1" value="b">b</option> <option id="widget-id-2" value="c">c</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest(form={'widget.name': ['c']}) >>> widget.update() >>> widget.extract() ('c',) When "No value" is selected, then no verification against the terms is done: >>> widget.request = TestRequest(form={'widget.name': ['--NOVALUE--']}) >>> widget.update() >>> widget.extract(default=1) ('--NOVALUE--',) Unfortunately, when nothing is selected, we do not get an empty list sent into the request, but simply no entry at all. For this we have the empty marker, so that: >>> widget.request = TestRequest(form={'widget.name-empty-marker': '1'}) >>> widget.update() >>> widget.extract() () If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract(default=1) 1 Let's now make sure that a bogus value causes extract to return the default as described by the interface: >>> widget.request = TestRequest(form={'widget.name': ['x']}) >>> widget.update() >>> widget.extract(default=1) 1 Custom No Value Messages ######################## Additionally to the standard dynamic attribute values, the select widget also allows dynamic values for the "No value message". Initially, we have the default message: >>> widget.noValueMessage 'No value' Let's now register an attribute value: >>> from z3c.form.widget import StaticWidgetAttribute >>> NoValueMessage = StaticWidgetAttribute('- nothing -') >>> import zope.component >>> zope.component.provideAdapter(NoValueMessage, name='noValueMessage') After updating the widget, the no value message changed to the value provided by the adapter: >>> widget.update() >>> widget.noValueMessage '- nothing -' Select json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'content': '- nothing -', 'id': 'widget-id-novalue', 'selected': True, 'value': '--NOVALUE--'}, {'content': 'a', 'id': 'widget-id-0', 'selected': False, 'value': 'a'}, {'content': 'b', 'id': 'widget-id-1', 'selected': False, 'value': 'b'}, {'content': 'c', 'id': 'widget-id-2', 'selected': False, 'value': 'c'}], 'required': False, 'type': 'select', 'value': ()} Explicit Selection Prompt ######################### In certain scenarios it is desirable to ask the user to select a value and display it as the first choice, such as "please select a value". In those cases you just have to set the ``prompt`` attribute to ``True``: >>> widget.prompt = True >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" value="--NOVALUE--" selected="selected">Select a value ...</option> <option id="widget-id-0" value="a">a</option> <option id="widget-id-1" value="b">b</option> <option id="widget-id-2" value="c">c</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> As you can see, even though the field is not required, only the explicit prompt is shown. However, the prompt will also be shown if the field is required: >>> widget.required = True >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget required" size="1"> <option id="widget-id-novalue" value="--NOVALUE--" selected="selected">Select a value ...</option> <option id="widget-id-0" value="a">a</option> <option id="widget-id-1" value="b">b</option> <option id="widget-id-2" value="c">c</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Since the prompy uses the "No value" as the value for the selection, all behavior is identical to selecting "No value". As for the no-value message, the prompt message, which is available under >>> widget.promptMessage 'Select a value ...' can also be changed using an attribute value adapter: >>> PromptMessage = StaticWidgetAttribute('Please select a value') >>> zope.component.provideAdapter(PromptMessage, name='promptMessage') So after updating the widget you have the custom value: >>> widget.update() >>> widget.promptMessage 'Please select a value' Additionally, the select widget also allows dynamic value for the ``prompt`` attribute . Initially, value is ``False``: >>> widget.prompt = False >>> widget.prompt False Let's now register an attribute value: >>> from z3c.form.widget import StaticWidgetAttribute >>> AllowPrompt = StaticWidgetAttribute(True) >>> import zope.component >>> zope.component.provideAdapter(AllowPrompt, name='prompt') After updating the widget, the value for the prompt attribute changed to the value provided by the adapter: >>> widget.update() >>> widget.prompt True Display Widget ############## The select widget comes with a template for ``DISPLAY_MODE``. Let's register it first: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) >>> widget.mode = interfaces.DISPLAY_MODE >>> widget.value = ['b', 'c'] >>> widget.update() >>> print(widget.render()) <span id="widget-id" class="select-widget required"> <span class="selected-option">b</span>, <span class="selected-option">c</span> </span> Let's see what happens if we have values that are not in the vocabulary: >>> widget.value = ['x', 'y'] >>> widget.update() >>> print(widget.render()) <span id="widget-id" class="select-widget required"></span> Hidden Widget ############# The select widget comes with a template for ``HIDDEN_MODE``. Let's register it first: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_hidden.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.HIDDEN_MODE) We can now set our widget's mode to hidden and render it: >>> widget.mode = interfaces.HIDDEN_MODE >>> widget.value = ['b'] >>> widget.update() >>> print(widget.render()) <input type="hidden" name="widget.name:list" class="hidden-widget" value="b" id="widget-id-1" /> <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's see what happens if we have values that are not in the vocabulary: >>> widget.value = ['x', 'y'] >>> widget.update() >>> print(widget.render()) <input name="widget.name-empty-marker" type="hidden" value="1" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/select.rst
select.rst
Button Widget ------------- The button widget allows you to provide buttons whose actions are defined using Javascript scripts. The "button" type of the "INPUT" element is described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-INPUT As for all widgets, the button widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import button >>> verifyClass(interfaces.IWidget, button.ButtonWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = button.ButtonWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget.id' >>> widget.name = 'widget.name' We also need to register the template for the widget: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('button_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IButtonWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get a simple input element: >>> print(widget.render()) <input type="button" id="widget.id" name="widget.name" class="button-widget" /> Setting a value for the widget effectively changes the button label: >>> widget.value = 'Button' >>> print(widget.render()) <input type="button" id="widget.id" name="widget.name" class="button-widget" value="Button" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest(form={'widget.name': 'button'}) >>> widget.update() >>> widget.extract() 'button' If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/button.rst
button.rst
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema import zope.schema.interfaces from zope.i18n import translate from z3c.form import interfaces from z3c.form.browser import widget from z3c.form.i18n import MessageFactory as _ from z3c.form.widget import FieldWidget from z3c.form.widget import SequenceWidget @zope.interface.implementer_only(interfaces.ISelectWidget) class SelectWidget(widget.HTMLSelectWidget, SequenceWidget): """Select widget implementation.""" klass = 'select-widget' css = 'select' prompt = False noValueMessage = _('No value') promptMessage = _('Select a value ...') # Internal attributes _adapterValueAttributes = SequenceWidget._adapterValueAttributes + \ ('noValueMessage', 'promptMessage', 'prompt') def isSelected(self, term): return term.token in self.value def update(self): """See z3c.form.interfaces.IWidget.""" super().update() widget.addFieldClass(self) @property def items(self): if self.terms is None: # update() has not been called yet return () items = [] if (not self.required or self.prompt) and self.multiple is None: message = self.noValueMessage if self.prompt: message = self.promptMessage items.append({ 'id': self.id + '-novalue', 'value': self.noValueToken, 'content': message, 'selected': self.value in ((), []) }) ignored = set(self.value) def addItem(idx, term, prefix=''): selected = self.isSelected(term) if selected and term.token in ignored: ignored.remove(term.token) id = '%s-%s%i' % (self.id, prefix, idx) content = term.token if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) items.append( {'id': id, 'value': term.token, 'content': content, 'selected': selected}) for idx, term in enumerate(self.terms): addItem(idx, term) if ignored: # some values are not displayed, probably they went away from the # vocabulary for idx, token in enumerate(sorted(ignored)): try: term = self.terms.getTermByToken(token) except LookupError: # just in case the term really went away continue addItem(idx, term, prefix='missing-') return items def json_data(self): data = super().json_data() data['options'] = self.items data['type'] = 'select' return data @zope.component.adapter(zope.schema.interfaces.IChoice, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def ChoiceWidgetDispatcher(field, request): """Dispatch widget for IChoice based also on its source.""" return zope.component.getMultiAdapter((field, field.vocabulary, request), interfaces.IFieldWidget) @zope.component.adapter(zope.schema.interfaces.IChoice, zope.interface.Interface, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def SelectFieldWidget(field, source, request=None): """IFieldWidget factory for SelectWidget.""" # BBB: emulate our pre-2.0 signature (field, request) if request is None: real_request = source else: real_request = request return FieldWidget(field, SelectWidget(real_request)) @zope.component.adapter( zope.schema.interfaces.IUnorderedCollection, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def CollectionSelectFieldWidget(field, request): """IFieldWidget factory for SelectWidget.""" widget = zope.component.getMultiAdapter((field, field.value_type, request), interfaces.IFieldWidget) widget.size = 5 widget.multiple = 'multiple' return widget @zope.component.adapter( zope.schema.interfaces.IUnorderedCollection, zope.schema.interfaces.IChoice, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def CollectionChoiceSelectFieldWidget(field, value_type, request): """IFieldWidget factory for SelectWidget.""" return SelectFieldWidget(field, None, request)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/select.py
select.py
Image Widget ------------ The image widget allows you to submit a form to the server by clicking on an image. The "image" type of the "INPUT" element is described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-INPUT As for all widgets, the image widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import image >>> verifyClass(interfaces.IWidget, image.ImageWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = image.ImageWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget.id' >>> widget.name = 'widget.name' We also need to register the template for the widget: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('image_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IImageWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get a simple input element: >>> print(widget.render()) <input type="image" id="widget.id" name="widget.name" class="image-widget" /> Setting an image source for the widget effectively changes the "src" attribute: >>> widget.src = u'widget.png' >>> print(widget.render()) <input type="image" id="widget.id" name="widget.name" class="image-widget" src="widget.png" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest( ... form={'widget.name.x': '10', ... 'widget.name.y': '20', ... 'widget.name': 'value'}) >>> widget.update() >>> sorted(widget.extract().items()) [('value', 'value'), ('x', 10), ('y', 20)] If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/image.rst
image.rst
Select Widget, missing terms ---------------------------- The select widget allows you to select one or more values from a set of given options. The "SELECT" and "OPTION" elements are described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-SELECT As for all widgets, the select widget must provide the new ``IWidget`` interface: >>> from z3c.form import interfaces >>> from z3c.form.browser import select The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = select.SelectWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) We need some context: >>> class IPerson(zope.interface.Interface): ... rating = zope.schema.Choice( ... vocabulary='Ratings') >>> @zope.interface.implementer(IPerson) ... class Person(object): ... pass >>> person = Person() Let's provide some values for this widget. We can do this by defining a source providing ``ITerms``. This source uses descriminators which will fit our setup. >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary >>> from zope.schema.vocabulary import SimpleTerm >>> import z3c.form.term >>> from zope.schema import vocabulary >>> ratings = vocabulary.SimpleVocabulary([ ... vocabulary.SimpleVocabulary.createTerm(0, '0', u'bad'), ... vocabulary.SimpleVocabulary.createTerm(1, '1', u'okay'), ... vocabulary.SimpleVocabulary.createTerm(2, '2', u'good') ... ]) >>> def RatingsVocabulary(obj): ... return ratings >>> vr = vocabulary.getVocabularyRegistry() >>> vr.register('Ratings', RatingsVocabulary) >>> class SelectionTerms(z3c.form.term.MissingChoiceTermsVocabulary): ... def __init__(self, context, request, form, field, widget): ... self.context = context ... self.field = field ... self.terms = ratings ... self.widget = widget ... ... def _makeMissingTerm(self, token): ... if token == 'x': ... return super(SelectionTerms, self)._makeMissingTerm(token) ... else: ... raise LookupError >>> zope.component.provideAdapter(SelectionTerms, ... (None, interfaces.IFormLayer, None, None, interfaces.ISelectWidget) ) >>> import z3c.form.datamanager >>> zope.component.provideAdapter(z3c.form.datamanager.AttributeField) Now let's try if we get widget values: >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" selected="selected" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="0">bad</option> <option id="widget-id-1" value="1">okay</option> <option id="widget-id-2" value="2">good</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> If we set the widget value to "x", then it should be present and selected: >>> widget.value = ('x',) >>> widget.context = person >>> widget.field = IPerson['rating'] >>> zope.interface.alsoProvides(widget, interfaces.IContextAware) >>> person.rating = 'x' >>> widget.terms = None >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="0">bad</option> <option id="widget-id-1" value="1">okay</option> <option id="widget-id-2" value="2">good</option> <option id="widget-id-missing-0" selected="selected" value="x">Missing: x</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> If we set the widget value to "y", then it should NOT be around: >>> widget.value = ['y'] >>> widget.update() >>> print(widget.render()) <select id="widget-id" name="widget.name:list" class="select-widget" size="1"> <option id="widget-id-novalue" value="--NOVALUE--">No value</option> <option id="widget-id-0" value="0">bad</option> <option id="widget-id-1" value="1">okay</option> <option id="widget-id-2" value="2">good</option> </select> <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's now make sure that we can extract user entered data from a widget: >>> widget.request = TestRequest(form={'widget.name': ['c']}) >>> widget.update() >>> widget.extract() <NO_VALUE> Well, only of it matches the context's current value: >>> widget.request = TestRequest(form={'widget.name': ['x']}) >>> widget.update() >>> widget.extract() ('x',) When "No value" is selected, then no verification against the terms is done: >>> widget.request = TestRequest(form={'widget.name': ['--NOVALUE--']}) >>> widget.update() >>> widget.extract(default=1) ('--NOVALUE--',) Let's now make sure that we can extract user entered missing data from a widget: >>> widget.request = TestRequest(form={'widget.name': ['x']}) >>> widget.update() >>> widget.extract() ('x',) >>> widget.request = TestRequest(form={'widget.name': ['y']}) >>> widget.update() >>> widget.extract() <NO_VALUE> Unfortunately, when nothing is selected, we do not get an empty list sent into the request, but simply no entry at all. For this we have the empty marker, so that: >>> widget.request = TestRequest(form={'widget.name-empty-marker': '1'}) >>> widget.update() >>> widget.extract() () If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract(default=1) 1 Let's now make sure that a bogus value causes extract to return the default as described by the interface: >>> widget.request = TestRequest(form={'widget.name': ['y']}) >>> widget.update() >>> widget.extract(default=1) 1 Display Widget ############## The select widget comes with a template for ``DISPLAY_MODE``. Let's register it first: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) Let's see what happens if we have values that are not in the vocabulary: >>> widget.required = True >>> widget.mode = interfaces.DISPLAY_MODE >>> widget.value = ['0', '1', 'x'] >>> widget.update() >>> print(widget.render()) <span id="widget-id" class="select-widget"> <span class="selected-option">bad</span>, <span class="selected-option">okay</span>, <span class="selected-option">Missing: x</span> </span> Hidden Widget ############# The select widget comes with a template for ``HIDDEN_MODE``. Let's register it first: >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('select_hidden.pt'), 'text/html'), ... (None, None, None, None, interfaces.ISelectWidget), ... IPageTemplate, name=interfaces.HIDDEN_MODE) Let's see what happens if we have values that are not in the vocabulary: >>> widget.mode = interfaces.HIDDEN_MODE >>> widget.value = ['0', 'x'] >>> widget.update() >>> print(widget.render()) <input id="widget-id-0" name="widget.name:list" value="0" class="hidden-widget" type="hidden" /> <input id="widget-id-missing-0" name="widget.name:list" value="x" class="hidden-widget" type="hidden" /> <input name="widget.name-empty-marker" type="hidden" value="1" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/select-missing-terms.rst
select-missing-terms.rst
"""Widget Framework Implementation.""" __docformat__ = "reStructuredText" import zope.interface from zope.schema.fieldproperty import FieldProperty from z3c.form.browser import interfaces from z3c.form.interfaces import INPUT_MODE from z3c.form.interfaces import IFieldWidget class WidgetLayoutSupport: """Widget layout support""" def wrapCSSClass(self, klass, pattern='%(class)s'): """Return a list of css class names wrapped with given pattern""" if klass is not None and pattern is not None: return [pattern % {'class': k} for k in klass.split()] else: return [] def getCSSClass(self, klass=None, error=None, required=None, classPattern='%(class)s', errorPattern='%(class)s-error', requiredPattern='%(class)s-required'): """Setup given css class (klass) with error and required postfix If no klass name is given the widget.wrapper class name/names get used. It is also possible if more then one (empty space separated) names are given as klass argument. This method can get used from your form or widget template or widget layout template without to re-implement the widget itself just because you a different CSS class concept. The following sample: <div tal:attributes="class python:widget.getCSSClass('foo bar')"> label widget and error </div> will render a div tag if the widget field defines required=True: <div class="foo-error bar-error foo-required bar-required foo bar"> label widget and error </div> And the following sample: <div tal:attributes="class python:widget.getCSSClass('row')"> label widget and error </div> will render a div tag if the widget field defines required=True and an error occurs: <div class="row-error row-required row"> label widget and error </div> Note; you need to define a globale widget property if you use python:widget (in your form template). And you need to use the view scope in your widget or layout templates. Note, you can set the pattern to None for skip error or required rendering. Or you can use a pattern like 'error' or 'required' if you like to skip postfixing your default css klass name for error or required rendering. """ classes = [] # setup class names if klass is not None: kls = klass else: kls = self.css # setup error class names if error is not None: error = error else: error = kls # setup required class names if required is not None: required = required else: required = kls # append error class names if self.error is not None: classes += self.wrapCSSClass(error, errorPattern) # append required class names if self.required: classes += self.wrapCSSClass(required, requiredPattern) # append given class names classes += self.wrapCSSClass(kls, classPattern) # remove duplicated class names but keep order unique = [] [unique.append(kls) for kls in classes if kls not in unique] return ' '.join(unique) @zope.interface.implementer(interfaces.IHTMLFormElement) class HTMLFormElement(WidgetLayoutSupport): id = FieldProperty(interfaces.IHTMLFormElement['id']) klass = FieldProperty(interfaces.IHTMLFormElement['klass']) style = FieldProperty(interfaces.IHTMLFormElement['style']) title = FieldProperty(interfaces.IHTMLFormElement['title']) lang = FieldProperty(interfaces.IHTMLFormElement['lang']) onclick = FieldProperty(interfaces.IHTMLFormElement['onclick']) ondblclick = FieldProperty(interfaces.IHTMLFormElement['ondblclick']) onmousedown = FieldProperty(interfaces.IHTMLFormElement['onmousedown']) onmouseup = FieldProperty(interfaces.IHTMLFormElement['onmouseup']) onmouseover = FieldProperty(interfaces.IHTMLFormElement['onmouseover']) onmousemove = FieldProperty(interfaces.IHTMLFormElement['onmousemove']) onmouseout = FieldProperty(interfaces.IHTMLFormElement['onmouseout']) onkeypress = FieldProperty(interfaces.IHTMLFormElement['onkeypress']) onkeydown = FieldProperty(interfaces.IHTMLFormElement['onkeydown']) onkeyup = FieldProperty(interfaces.IHTMLFormElement['onkeyup']) disabled = FieldProperty(interfaces.IHTMLFormElement['disabled']) tabindex = FieldProperty(interfaces.IHTMLFormElement['tabindex']) onfocus = FieldProperty(interfaces.IHTMLFormElement['onfocus']) onblur = FieldProperty(interfaces.IHTMLFormElement['onblur']) onchange = FieldProperty(interfaces.IHTMLFormElement['onchange']) # layout support css = FieldProperty(interfaces.IHTMLFormElement['css']) def addClass(self, klass: str): """Add a class to the HTML element. See interfaces.IHTMLFormElement. """ if not self.klass: self.klass = str(klass) else: # make sure items are not repeated parts = self.klass.split() + klass.split() # Remove duplicates and keep order. # Dictionaries are ordered in Python 3.7+ parts = list(dict.fromkeys(parts)) self.klass = " ".join(parts) def update(self): """See z3c.form.interfaces.IWidget""" super().update() if self.mode == INPUT_MODE and self.required: self.addClass('required') @property def _html_attributes(self) -> list: """Return a list of HTML attributes managed by this class.""" # This is basically a list of all the FieldProperty names except for # the `css` property, which is not an HTML attribute. return [ "id", "klass", # will be changed to `class` "style", "title", "lang", "onclick", "ondblclick", "onmousedown", "onmouseup", "onmouseover", "onmousemove", "onmouseout", "onkeypress", "onkeydown", "onkeyup", "disabled", "tabindex", "onfocus", "onblur", "onchange", ] _attributes = None @property def attributes(self) -> dict: # If `attributes` were explicitly set, return them. if isinstance(self._attributes, dict): return self._attributes # Otherwise return the default set of non-empty HTML attributes. attributes_items = [ ("class" if attr == "klass" else attr, getattr(self, attr, None)) for attr in self._html_attributes ] self._attributes = {key: val for key, val in attributes_items if val} return self._attributes @attributes.setter def attributes(self, value: dict): # Store the explicitly set attributes. self._attributes = value @zope.interface.implementer(interfaces.IHTMLInputWidget) class HTMLInputWidget(HTMLFormElement): readonly = FieldProperty(interfaces.IHTMLInputWidget['readonly']) alt = FieldProperty(interfaces.IHTMLInputWidget['alt']) accesskey = FieldProperty(interfaces.IHTMLInputWidget['accesskey']) onselect = FieldProperty(interfaces.IHTMLInputWidget['onselect']) @property def _html_attributes(self) -> list: attributes = super()._html_attributes attributes.extend( [ "readonly", "alt", "accesskey", "onselect", ] ) return attributes @zope.interface.implementer(interfaces.IHTMLTextInputWidget) class HTMLTextInputWidget(HTMLInputWidget): size = FieldProperty(interfaces.IHTMLTextInputWidget['size']) maxlength = FieldProperty(interfaces.IHTMLTextInputWidget['maxlength']) placeholder = FieldProperty(interfaces.IHTMLTextInputWidget['placeholder']) autocapitalize = FieldProperty( interfaces.IHTMLTextInputWidget['autocapitalize']) @property def _html_attributes(self) -> list: attributes = super()._html_attributes attributes.extend( [ "size", "maxlength", "placeholder", "autocapitalize", ] ) return attributes @zope.interface.implementer(interfaces.IHTMLTextAreaWidget) class HTMLTextAreaWidget(HTMLFormElement): rows = FieldProperty(interfaces.IHTMLTextAreaWidget['rows']) cols = FieldProperty(interfaces.IHTMLTextAreaWidget['cols']) readonly = FieldProperty(interfaces.IHTMLTextAreaWidget['readonly']) accesskey = FieldProperty(interfaces.IHTMLTextAreaWidget['accesskey']) onselect = FieldProperty(interfaces.IHTMLTextAreaWidget['onselect']) @property def _html_attributes(self) -> list: attributes = super()._html_attributes attributes.extend( [ "rows", "cols", "readonly", "accesskey", "onselect", ] ) return attributes @zope.interface.implementer(interfaces.IHTMLSelectWidget) class HTMLSelectWidget(HTMLFormElement): multiple = FieldProperty(interfaces.IHTMLSelectWidget['multiple']) size = FieldProperty(interfaces.IHTMLSelectWidget['size']) @property def _html_attributes(self) -> list: attributes = super()._html_attributes attributes.extend( [ "multiple", "size", ] ) return attributes def addFieldClass(widget): """Add a class to the widget that is based on the field type name. If the widget does not have field, then nothing is done. """ if IFieldWidget.providedBy(widget): klass = str(widget.field.__class__.__name__.lower() + '-field') widget.addClass(klass)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/widget.py
widget.py
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema import zope.schema.interfaces from zope.i18n import translate from zope.pagetemplate.interfaces import IPageTemplate from zope.schema.vocabulary import SimpleTerm from z3c.form import interfaces from z3c.form import util from z3c.form.browser import widget from z3c.form.widget import FieldWidget from z3c.form.widget import SequenceWidget @zope.interface.implementer_only(interfaces.IRadioWidget) class RadioWidget(widget.HTMLInputWidget, SequenceWidget): """Input type radio widget implementation.""" klass = 'radio-widget' css = 'radio' def isChecked(self, term): return term.token in self.value def renderForValue(self, value): terms = list(self.terms) try: term = self.terms.getTermByToken(value) except LookupError: if value == SequenceWidget.noValueToken: term = SimpleTerm(value) terms.insert(0, term) id = '%s-novalue' % self.id else: raise else: id = '%s-%i' % (self.id, terms.index(term)) checked = self.isChecked(term) item = {'id': id, 'name': self.name, 'value': term.token, 'checked': checked} template = zope.component.getMultiAdapter( (self.context, self.request, self.form, self.field, self), IPageTemplate, name=self.mode + '_single') return template(self, item) @property def items(self): if self.terms is None: return for count, term in enumerate(self.terms): checked = self.isChecked(term) id = '%s-%i' % (self.id, count) if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) yield {'id': id, 'name': self.name, 'value': term.token, 'label': label, 'checked': checked} def update(self): """See z3c.form.interfaces.IWidget.""" super().update() widget.addFieldClass(self) def json_data(self): data = super().json_data() data['options'] = list(self.items) data['type'] = 'radio' return data @zope.component.adapter(zope.schema.interfaces.IField, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def RadioFieldWidget(field, request): """IFieldWidget factory for RadioWidget.""" return FieldWidget(field, RadioWidget(request))
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/radio.py
radio.py
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema import zope.schema.interfaces from zope.i18n import translate from zope.schema import vocabulary from z3c.form import interfaces from z3c.form import term from z3c.form import util from z3c.form.browser import widget from z3c.form.widget import FieldWidget from z3c.form.widget import SequenceWidget @zope.interface.implementer_only(interfaces.ICheckBoxWidget) class CheckBoxWidget(widget.HTMLInputWidget, SequenceWidget): """Input type checkbox widget implementation.""" klass = 'checkbox-widget' css = 'checkbox' items = () def isChecked(self, term): return term.token in self.value @property def items(self): if self.terms is None: return () items = [] for count, term_ in enumerate(self.terms): checked = self.isChecked(term_) id = '%s-%i' % (self.id, count) if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term_): label = translate(term_.title, context=self.request, default=term_.title) else: label = util.toUnicode(term_.value) items.append( {'id': id, 'name': self.name + ':list', 'value': term_.token, 'label': label, 'checked': checked}) return items def update(self): """See z3c.form.interfaces.IWidget.""" super().update() widget.addFieldClass(self) def json_data(self): data = super().json_data() data['options'] = list(self.items) data['type'] = 'check' return data @zope.component.adapter(zope.schema.interfaces.IField, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def CheckBoxFieldWidget(field, request): """IFieldWidget factory for CheckBoxWidget.""" return FieldWidget(field, CheckBoxWidget(request)) @zope.interface.implementer_only(interfaces.ISingleCheckBoxWidget) class SingleCheckBoxWidget(CheckBoxWidget): """Single Input type checkbox widget implementation.""" klass = 'single-checkbox-widget' def updateTerms(self): if self.terms is None: self.terms = term.Terms() self.terms.terms = vocabulary.SimpleVocabulary(( vocabulary.SimpleTerm('selected', 'selected', self.label or self.field.title), )) return self.terms @zope.component.adapter(zope.schema.interfaces.IBool, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def SingleCheckBoxFieldWidget(field, request): """IFieldWidget factory for CheckBoxWidget.""" widget = FieldWidget(field, SingleCheckBoxWidget(request)) widget.label = '' # don't show the label twice return widget
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/checkbox.py
checkbox.py
Radio Widget ------------ The RadioWidget renders a radio input type field e.g. <input type="radio" /> >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import radio The RadioWidget is a widget: >>> verifyClass(interfaces.IWidget, radio.RadioWidget) True The widget can render a input field only by adapting a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = radio.RadioWidget(request) Set a name and id for the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Such a field provides IWidget: >>> interfaces.IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import z3c.form.browser >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') >>> template_single = os.path.join( ... os.path.dirname(z3c.form.browser.__file__), ... 'radio_input_single.pt') >>> zope.component.provideAdapter( ... z3c.form.widget.WidgetTemplateFactory(template_single), ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input_single') If we render the widget we only get the empty marker: >>> print(widget.render()) <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's provide some values for this widget. We can do this by defining a source providing ITerms. This source uses discriminators which will fit for our setup. >>> import zope.schema.interfaces >>> import z3c.form.term >>> from zc.sourcefactory.basic import BasicSourceFactory >>> class YesNoSourceFactory(BasicSourceFactory): ... def getValues(self): ... return ['yes', 'no'] >>> class MyTerms(z3c.form.term.ChoiceTermsSource): ... def __init__(self, context, request, form, field, widget): ... self.terms = YesNoSourceFactory() >>> zope.component.provideAdapter(z3c.form.term.BoolTerms, ... adapts=(zope.interface.Interface, ... interfaces.IFormLayer, zope.interface.Interface, ... zope.interface.Interface, interfaces.IRadioWidget)) Now let's try if we get widget values: >>> widget.update() >>> print(widget.render()) <span class="option"> <label for="widget-id-0"> <input type="radio" id="widget-id-0" name="widget.name" class="radio-widget" value="true" /> <span class="label">yes</span> </label> </span><span class="option"> <label for="widget-id-1"> <input type="radio" id="widget-id-1" name="widget.name" class="radio-widget" value="false" /> <span class="label">no</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The radio json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'checked': False, 'id': 'widget-id-0', 'label': 'yes', 'name': 'widget.name', 'value': 'true'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name', 'value': 'false'}], 'required': False, 'type': 'radio', 'value': ()} If we set the value for the widget to ``yes``, we can se that the radio field get rendered with a checked flag: >>> widget.value = 'true' >>> widget.update() >>> print(widget.render()) <span class="option"> <label for="widget-id-0"> <input type="radio" id="widget-id-0" name="widget.name" class="radio-widget" value="true" checked="checked" /> <span class="label">yes</span> </label> </span><span class="option"> <label for="widget-id-1"> <input type="radio" id="widget-id-1" name="widget.name" class="radio-widget" value="false" /> <span class="label">no</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The radio json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'checked': True, 'id': 'widget-id-0', 'label': 'yes', 'name': 'widget.name', 'value': 'true'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name', 'value': 'false'}], 'required': False, 'type': 'radio', 'value': 'true'} We can also render the input elements for each value separately: >>> print(widget.renderForValue('true')) <input id="widget-id-0" name="widget.name" class="radio-widget" value="true" checked="checked" type="radio" /> >>> print(widget.renderForValue('false')) <input id="widget-id-1" name="widget.name" class="radio-widget" value="false" type="radio" /> Additionally we can render the "no value" input element used for non-required fields: >>> from z3c.form.widget import SequenceWidget >>> print(SequenceWidget.noValueToken) --NOVALUE-- >>> print(widget.renderForValue(SequenceWidget.noValueToken)) <input id="widget-id-novalue" name="widget.name" class="radio-widget" value="--NOVALUE--" type="radio" /> Check HIDDEN_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_hidden.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden') >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_hidden_single.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden_single') >>> widget.value = ['true'] >>> widget.mode = interfaces.HIDDEN_MODE >>> print(widget.render()) <input id="widget-id-0" name="widget.name" value="true" class="hidden-widget" type="hidden" /> And independently: >>> print(widget.renderForValue('true')) <input id="widget-id-0" name="widget.name" value="true" class="hidden-widget" type="hidden" /> The unchecked values do not need a hidden field, hence they are empty: >>> print(widget.renderForValue('false')) Check DISPLAY_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_display.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='display') >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_display_single.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='display_single') >>> widget.value = ['true'] >>> widget.mode = interfaces.DISPLAY_MODE >>> print(widget.render()) <span id="widget-id" class="radio-widget"> <span class="selected-option">yes</span> </span> And independently: >>> print(widget.renderForValue('true')) <span id="widget-id" class="radio-widget"><span class="selected-option">yes</span></span> Again, unchecked values are not displayed: >>> print(widget.renderForValue('false')) Make sure that we produce a proper label when we have no title for a term and the value (which is used as a backup label) contains non-ASCII characters: >>> from zope.schema.vocabulary import SimpleVocabulary >>> terms = SimpleVocabulary.fromValues([b'yes\012', b'no\243']) >>> widget.terms = terms >>> widget.update() >>> pprint(list(widget.items)) [{'checked': False, 'id': 'widget-id-0', 'label': 'yes\n', 'name': 'widget.name', 'value': 'yes\n'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name', 'value': 'no...'}] Note: The "\234" character is interpreted differently in Pytohn 2 and 3 here. (This is mostly due to changes int he SimpleVocabulary code.) Term with non ascii __str__ ########################### Check if a term which __str__ returns non ascii string does not crash the update method >>> request = TestRequest() >>> widget = radio.RadioWidget(request) >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'radio_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary,SimpleTerm >>> import z3c.form.term >>> class ObjWithNonAscii__str__: ... def __str__(self): ... return 'héhé!' >>> class MyTerms(z3c.form.term.ChoiceTermsVocabulary): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary([ ... SimpleTerm(ObjWithNonAscii__str__(), 'one', 'One'), ... SimpleTerm(ObjWithNonAscii__str__(), 'two', 'Two'), ... ]) >>> zope.component.provideAdapter(MyTerms, ... adapts=(zope.interface.Interface, ... interfaces.IFormLayer, zope.interface.Interface, ... zope.interface.Interface, interfaces.IRadioWidget)) >>> widget.update() >>> print(widget.render()) <html> <body> <span class="option"> <label for="widget-id-0"> <input class="radio-widget" id="widget-id-0" name="widget.name" type="radio" value="one"> <span class="label">One</span> </label> </span> <span class="option"> <label for="widget-id-1"> <input class="radio-widget" id="widget-id-1" name="widget.name" type="radio" value="two"> <span class="label">Two</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1"> </body> </html>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/radio.rst
radio.rst
File Widget ----------- The file widget allows you to upload a new file to the server. The "file" type of the "INPUT" element is described here: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#edef-INPUT As for all widgets, the file widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import file >>> verifyClass(interfaces.IWidget, file.FileWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = file.FileWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget.id' >>> widget.name = 'widget.name' We also need to register the template for the widget: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('file_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IFileWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get a simple input element: >>> print(widget.render()) <input type="file" id="widget.id" name="widget.name" class="file-widget" /> Let's now make sure that we can extract user entered data from a widget: >>> from io import BytesIO >>> myfile = BytesIO(b'My file contents.') >>> widget.request = TestRequest(form={'widget.name': myfile}) >>> widget.update() >>> isinstance(widget.extract(), BytesIO) True If nothing is found in the request, the default is returned: >>> widget.request = TestRequest() >>> widget.update() >>> widget.extract() <NO_VALUE> Make also sure that we can handle FileUpload objects given form a file upload. >>> from zope.publisher.browser import FileUpload Let's define a FieldStorage stub: >>> class FieldStorageStub: ... def __init__(self, file): ... self.file = file ... self.headers = {} ... self.filename = 'foo.bar' Now build a FileUpload: >>> myfile = BytesIO(b'File upload contents.') >>> aFieldStorage = FieldStorageStub(myfile) >>> myUpload = FileUpload(aFieldStorage) >>> widget.request = TestRequest(form={'widget.name': myUpload}) >>> widget.update() >>> widget.extract() <zope.publisher.browser.FileUpload object at ...> If we render them, we get a regular file upload widget: >>> print(widget.render()) <input type="file" id="widget.id" name="widget.name" class="file-widget" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/file.rst
file.rst
ObjectWidget ------------ The `ObjectWidget` widget is about rendering a schema's fields as a single widget. There are way too many preconditions to exercise the `ObjectWidget` as it relies heavily on the from and widget framework. It renders the sub-widgets in a sub-form. In order to not overwhelm you with our set of well-chosen defaults, all the default component registrations have been made prior to doing those examples: >>> from z3c.form import testing >>> testing.setupFormDefaults() >>> import zope.component >>> from z3c.form import datamanager >>> zope.component.provideAdapter(datamanager.DictionaryField) >>> from z3c.form.testing import IMySubObject >>> from z3c.form.testing import IMySecond >>> from z3c.form.testing import MySubObject >>> from z3c.form.testing import MySecond >>> import z3c.form.object >>> zope.component.provideAdapter(z3c.form.object.ObjectConverter) >>> from z3c.form.error import MultipleErrorViewSnippet >>> zope.component.provideAdapter(MultipleErrorViewSnippet) As for all widgets, the objectwidget must provide the new `IWidget` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> import z3c.form.browser.object >>> verifyClass(interfaces.IWidget, z3c.form.browser.object.ObjectWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = z3c.form.browser.object.ObjectWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Also, stand-alone widgets need to ignore the context: >>> widget.ignoreContext = True There is no life for ObjectWidget without a schema to render: >>> widget.update() Traceback (most recent call last): ... ValueError: <ObjectWidget 'widget.name'> .field is None, that's a blocking point This schema is specified by the field: >>> from z3c.form.widget import FieldWidget >>> from z3c.form.testing import IMySubObject >>> import zope.schema >>> field = zope.schema.Object( ... __name__='subobject', ... title='my object widget', ... schema=IMySubObject) Apply the field nicely with the helper: >>> widget = FieldWidget(field, widget) We also need to register the templates for the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('object_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.IObjectWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('object_display.pt'), 'text/html'), ... (None, None, None, None, interfaces.IObjectWidget), ... IPageTemplate, name=interfaces.DISPLAY_MODE) We can now render the widget: >>> widget.update() >>> print(widget.render()) <html> <body> <div class="object-widget required"> <div class="label"> <label for="subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="subobject-widgets-foofield" name="subobject.widgets.foofield" type="text" value="1,111"> </div> <div class="label"> <label for="subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="subobject-widgets-barfield" name="subobject.widgets.barfield" type="text" value="2,222"> </div> <input name="subobject-empty-marker" type="hidden" value="1"> </div> </body> </html> As you see all sort of default values are rendered. Let's provide a more meaningful value: >>> from z3c.form.testing import MySubObject >>> v = MySubObject() >>> v.foofield = 42 >>> v.barfield = 666 >>> v.__marker__ = "ThisMustStayTheSame" >>> widget.ignoreContext = False >>> widget.value = dict(foofield='42', barfield='666') >>> widget.update() >>> print(widget.render()) <html> <body> <div class="object-widget required"> <div class="label"> <label for="subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="subobject-widgets-foofield" name="subobject.widgets.foofield" type="text" value="42"> </div> <div class="label"> <label for="subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="subobject-widgets-barfield" name="subobject.widgets.barfield" type="text" value="666"> </div> <input name="subobject-empty-marker" type="hidden" value="1"> </div> </body> </html> The widget's value is NO_VALUE until it gets a request: >>> widget.value <NO_VALUE> Let's fill in some values via the request: >>> widget.request = TestRequest(form={'subobject.widgets.foofield':'2', ... 'subobject.widgets.barfield':'999', ... 'subobject-empty-marker':'1'}) >>> widget.update() >>> print(widget.render()) <html> <body> <div class="object-widget required"> <div class="label"> <label for="subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="subobject-widgets-foofield" name="subobject.widgets.foofield" type="text" value="2"> </div> <div class="label"> <label for="subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="subobject-widgets-barfield" name="subobject.widgets.barfield" type="text" value="999"> </div> <input name="subobject-empty-marker" type="hidden" value="1"> </div> </body> </html> Widget value comes from the request: >>> wv = widget.value >>> pprint(wv) {'barfield': '999', 'foofield': '2'} But our object will not be modified, since there was no "apply"-like control. >>> v <z3c.form.testing.MySubObject object at ...> >>> v.foofield 42 >>> v.barfield 666 The marker must stay (we have to modify the same object): >>> v.__marker__ 'ThisMustStayTheSame' >>> converter = interfaces.IDataConverter(widget) >>> value = converter.toFieldValue(wv) Traceback (most recent call last): ... RuntimeError: No IObjectFactory adapter registered for z3c.form.testing.IMySubObject We have to register object factory adapters to allow the objectwidget to create objects: >>> from z3c.form.object import registerFactoryAdapter >>> registerFactoryAdapter(IMySubObject, MySubObject) >>> registerFactoryAdapter(IMySecond, MySecond) >>> value = converter.toFieldValue(wv) >>> value <z3c.form.testing.MySubObject object at ...> >>> value.foofield 2 >>> value.barfield 999 This is a different object: >>> value.__marker__ Traceback (most recent call last): ... AttributeError: 'MySubObject' object has no attribute '__marker__' Setting missing values on the widget works too: >>> widget.value = converter.toWidgetValue(field.missing_value) >>> widget.update() Default values get rendered: >>> print(widget.render()) <div class="object-widget required"> <div class="label"> <label for="subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="subobject-widgets-foofield" name="subobject.widgets.foofield" class="text-widget required int-field" value="2" type="text" /> </div> <div class="label"> <label for="subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input id="subobject-widgets-barfield" name="subobject.widgets.barfield" class="text-widget int-field" value="999" type="text" /> </div> <input name="subobject-empty-marker" type="hidden" value="1" /> </div> But on the return we get default values back: >>> pprint(widget.value) {'barfield': '999', 'foofield': '2'} >>> value = converter.toFieldValue(widget.value) >>> value <z3c.form.testing.MySubObject object at ...> HMMMM.... do we have to test error handling here? I'm tempted to leave it out as no widgets seem to do this. #Error handling is next. Let's use the value "bad" (an invalid integer literal) #as input for our internal (sub) widget. # # >>> widget.request = TestRequest(form={'subobject.widgets.foofield':'55', # ... 'subobject.widgets.barfield':'bad', # ... 'subobject-empty-marker':'1'}) # # # >>> widget.update() # >>> print(widget.render()) # <html> # <body> # <div class="object-widget required"> # <div class="label"> # <label for="subobject-widgets-foofield"> # <span>My foo field</span> # <span class="required">*</span> # </label> # </div> # <div class="widget"> # <input class="text-widget required int-field" # id="subobject-widgets-foofield" # name="subobject.widgets.foofield" # type="text" value="55"> # </div> # <div class="label"> # <label for="subobject-widgets-barfield"> # <span>My dear bar</span> # </label> # </div> # <div class="error">The entered value is not a valid integer literal.</div> # <div class="widget"> # <input class="text-widget int-field" # id="subobject-widgets-barfield" # name="subobject.widgets.barfield" # type="text" value="bad"> # </div> # <input name="subobject-empty-marker" type="hidden" value="1"> # </div> # </body> # </html> # #Getting the widget value raises the widget errors: # # >>> widget.value # Traceback (most recent call last): # ... # MultipleErrors # #Our object still must retain the old values: # # >>> v # <z3c.form.testing.MySubObject object at ...> # >>> v.foofield # 42 # >>> v.barfield # 666 # >>> v.__marker__ # 'ThisMustStayTheSame' In forms ======== Do all that fun in add and edit forms too: We have to provide an adapter first: >>> zope.component.provideAdapter(z3c.form.browser.object.ObjectFieldWidget) Forms and our objectwidget fire events on add and edit, setup a subscriber for those: >>> eventlog = [] >>> import zope.lifecycleevent >>> @zope.component.adapter(zope.lifecycleevent.ObjectModifiedEvent) ... def logEvent(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent) >>> @zope.component.adapter(zope.lifecycleevent.ObjectCreatedEvent) ... def logEvent2(event): ... eventlog.append(event) >>> zope.component.provideHandler(logEvent2) >>> def printEvents(): ... for event in eventlog: ... print(str(event)) ... if isinstance(event, zope.lifecycleevent.ObjectModifiedEvent): ... for attr in event.descriptions: ... print(attr.interface) ... print(sorted(attr.attributes)) We define an interface containing a subobject, and an addform for it: >>> from z3c.form import form, field >>> from z3c.form.testing import MyObject, IMyObject Note, that creating an object will print(some information about it:) >>> class MyAddForm(form.AddForm): ... fields = field.Fields(IMyObject) ... def create(self, data): ... print("MyAddForm.create") ... pprint(data) ... return MyObject(**data) ... def add(self, obj): ... self.context[obj.name] = obj ... def nextURL(self): ... pass We create the form and try to update it: >>> request = TestRequest() >>> myaddform = MyAddForm(root, request) >>> myaddform.update() As usual, the form contains a widget manager with the expected widget >>> list(myaddform.widgets.keys()) ['subobject', 'name'] >>> list(myaddform.widgets.values()) [<ObjectWidget 'form.widgets.subobject'>, <TextWidget 'form.widgets.name'>] The widget has sub-widgets: >>> list(myaddform.widgets['subobject'].widgets.keys()) ['foofield', 'barfield'] If we want to render the addform, we must give it a template: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate >>> from z3c.form import tests >>> def addTemplate(form): ... form.template = BoundPageTemplate( ... ViewPageTemplateFile( ... 'simple_edit.pt', os.path.dirname(tests.__file__)), form) >>> addTemplate(myaddform) Now rendering the addform renders the subform as well: >>> print(myaddform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="1,111"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="2,222"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value=""> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-add" name="form.buttons.add" type="submit" value="Add"> </div> </form> </body> </html> We don't have the object (yet) in the root: >>> root['first'] Traceback (most recent call last): ... KeyError: 'first' Let's try to add an object: >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'66', ... 'form.widgets.subobject.widgets.barfield':'99', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.add':'Add'}) >>> myaddform.request = request >>> myaddform.update() MyAddForm.create {'name': 'first', 'subobject': <z3c.form.testing.MySubObject object at ...>} Wow, it got added: >>> root['first'] <z3c.form.testing.MyObject object at ...> >>> root['first'].subobject <z3c.form.testing.MySubObject object at ...> Field values need to be right: >>> root['first'].subobject.foofield 66 >>> root['first'].subobject.barfield 99 Let's see our event log: >>> len(eventlog) 4 >>> printEvents() <zope...ObjectCreatedEvent object at ...> <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObject ['barfield', 'foofield'] <zope...ObjectCreatedEvent object at ...> <zope...contained.ContainerModifiedEvent object at ...> >>> eventlog=[] Let's try to edit that newly added object: >>> class MyEditForm(form.EditForm): ... fields = field.Fields(IMyObject) >>> editform = MyEditForm(root['first'], TestRequest()) >>> addTemplate(editform) >>> editform.update() Watch for the widget values in the HTML: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="66"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="99"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's modify the values: >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'43', ... 'form.widgets.subobject.widgets.barfield':'55', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.apply':'Apply'}) They are still the same: >>> root['first'].subobject.foofield 66 >>> root['first'].subobject.barfield 99 >>> editform.request = request >>> editform.update() Until we have updated the form: >>> root['first'].subobject.foofield 43 >>> root['first'].subobject.barfield 55 Let's see our event log: >>> len(eventlog) 2 >>> printEvents() <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObject ['barfield', 'foofield'] <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMyObject ['subobject'] >>> eventlog=[] After the update the form says that the values got updated and renders the new values: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>Data successfully updated.</i> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="43"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="55"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's see if the widget keeps the old object on editing: We add a special property to keep track of the object: >>> root['first'].__marker__ = "ThisMustStayTheSame" >>> root['first'].subobject.foofield 43 >>> root['first'].subobject.barfield 55 Let's modify the values: >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'666', ... 'form.widgets.subobject.widgets.barfield':'999', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.apply':'Apply'}) >>> editform.request = request >>> editform.update() Let's check what are ther esults of the update: >>> root['first'].subobject.foofield 666 >>> root['first'].subobject.barfield 999 >>> root['first'].__marker__ 'ThisMustStayTheSame' Let's make a nasty error, by typing 'bad' instead of an integer: >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'99', ... 'form.widgets.subobject.widgets.barfield':'bad', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.apply':'Apply'}) >>> editform.request = request >>> eventlog=[] >>> editform.update() Eventlog must be clean: >>> len(eventlog) 0 Watch for the error message in the HTML: it has to appear at the field itself and at the top of the form: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> my object: <div class="error">The entered value is not a valid integer literal.</div> </li> </ul> <form action="."> <div class="row"> <b> <div class="error">The entered value is not a valid integer literal.</div> </b> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="99"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="bad"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> The object values must stay at the old ones: >>> root['first'].subobject.foofield 666 >>> root['first'].subobject.barfield 999 Let's make more errors: Now we enter 'bad' and '999999', where '999999' hits the upper limit of the field. >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'999999', ... 'form.widgets.subobject.widgets.barfield':'bad', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.apply':'Apply'}) >>> editform.request = request >>> editform.update() Both errors must appear at the top of the form: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> my object: <div class="error">Value is too big</div> <div class="error">The entered value is not a valid integer literal.</div> </li> </ul> <form action="."> <div class="row"> <b> <div class="error">Value is too big</div> <div class="error">The entered value is not a valid integer literal.</div> </b> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="error">Value is too big</div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="999999"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="error">The entered value is not a valid integer literal.</div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="bad"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="first"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> And of course, the object values do not get modified: >>> root['first'].subobject.foofield 666 >>> root['first'].subobject.barfield 999 Simple but often used use-case is the display form: >>> editform = MyEditForm(root['first'], TestRequest()) >>> addTemplate(editform) >>> editform.mode = interfaces.DISPLAY_MODE >>> editform.update() >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <span class="text-widget int-field" id="form-widgets-subobject-widgets-foofield">666</span> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <span class="text-widget int-field" id="form-widgets-subobject-widgets-barfield">999</span> </div> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <span class="text-widget textline-field" id="form-widgets-name">first</span> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's see what happens in HIDDEN_MODE: (not quite sane thing, but we want to see the objectwidget rendered in hidden mode) >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('object_hidden.pt'), 'text/html'), ... (None, None, None, None, interfaces.IObjectWidget), ... IPageTemplate, name=interfaces.HIDDEN_MODE) >>> editform = MyEditForm(root['first'], TestRequest()) >>> addTemplate(editform) >>> editform.mode = interfaces.HIDDEN_MODE >>> editform.update() Note, that the labels and the button is there because the form template for testing does/should not care about the form being hidden. What matters is that the objectwidget is rendered hidden. >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <input id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" value="666" class="hidden-widget" type="hidden" /> <input id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" value="999" class="hidden-widget" type="hidden" /> </div> <div class="row"> <label for="form-widgets-name">name</label> <input id="form-widgets-name" name="form.widgets.name" value="first" class="hidden-widget" type="hidden" /> </div> <div class="action"> <input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" /> </div> </form> </body> </html> Editforms might use dicts as context: >>> newsub = MySubObject() >>> newsub.foofield = 78 >>> newsub.barfield = 87 >>> class MyEditFormDict(form.EditForm): ... fields = field.Fields(IMyObject) ... def getContent(self): ... return {'subobject': newsub, 'name': 'blooki'} >>> editform = MyEditFormDict(None, TestRequest()) >>> addTemplate(editform) >>> editform.update() Watch for the widget values in the HTML: >>> print(editform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-foofield" name="form.widgets.subobject.widgets.foofield" type="text" value="78"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-barfield" name="form.widgets.subobject.widgets.barfield" type="text" value="87"> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value="blooki"> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-apply" name="form.buttons.apply" type="submit" value="Apply"> </div> </form> </body> </html> Let's modify the values: >>> request = TestRequest(form={ ... 'form.widgets.subobject.widgets.foofield':'43', ... 'form.widgets.subobject.widgets.barfield':'55', ... 'form.widgets.name':'first', ... 'form.widgets.subobject-empty-marker':'1', ... 'form.buttons.apply':'Apply'}) They are still the same: >>> newsub.foofield 78 >>> newsub.barfield 87 Until updating the form: >>> editform.request = request >>> eventlog=[] >>> editform.update() >>> newsub.foofield 43 >>> newsub.barfield 55 >>> len(eventlog) 2 >>> printEvents() <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMySubObject ['barfield', 'foofield'] <zope...ObjectModifiedEvent object at ...> z3c.form.testing.IMyObject ['name', 'subobject'] Object in an Object situation ============================= We define an interface containing a subobject, and an addform for it: >>> from z3c.form import form, field >>> from z3c.form.testing import IMyComplexObject Note, that creating an object will print some information about it: >>> class MyAddForm(form.AddForm): ... fields = field.Fields(IMyComplexObject) ... def create(self, data): ... print("MyAddForm.create", str(data)) ... return MyObject(**data) ... def add(self, obj): ... self.context[obj.name] = obj ... def nextURL(self): ... pass We create the form and try to update it: >>> request = TestRequest() >>> myaddform = MyAddForm(root, request) >>> myaddform.update() As usual, the form contains a widget manager with the expected widget >>> list(myaddform.widgets.keys()) ['subobject', 'name'] >>> list(myaddform.widgets.values()) [<ObjectWidget 'form.widgets.subobject'>, <TextWidget 'form.widgets.name'>] The addform has our ObjectWidget which in turn contains the sub-widgets: >>> list(myaddform.widgets['subobject'].widgets.keys()) ['subfield', 'moofield'] >>> list(myaddform.widgets['subobject'].widgets['subfield'].widgets.keys()) ['foofield', 'barfield'] If we want to render the addform, we must give it a template: >>> addTemplate(myaddform) Now rendering the addform renders the subform as well: >>> print(myaddform.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-subobject">my object</label> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-subfield"> <span>Second-subobject</span> <span class="required">*</span> </label> </div> <div class="widget"> <div class="object-widget required"> <div class="label"> <label for="form-widgets-subobject-widgets-subfield-widgets-foofield"> <span>My foo field</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required int-field" id="form-widgets-subobject-widgets-subfield-widgets-foofield" name="form.widgets.subobject.widgets.subfield.widgets.foofield" type="text" value="1,111"> </div> <div class="label"> <label for="form-widgets-subobject-widgets-subfield-widgets-barfield"> <span>My dear bar</span> </label> </div> <div class="widget"> <input class="text-widget int-field" id="form-widgets-subobject-widgets-subfield-widgets-barfield" name="form.widgets.subobject.widgets.subfield.widgets.barfield" type="text" value="2,222"> </div> <input name="form.widgets.subobject.widgets.subfield-empty-marker" type="hidden" value="1"> </div> </div> <div class="label"> <label for="form-widgets-subobject-widgets-moofield"> <span>Something</span> <span class="required">*</span> </label> </div> <div class="widget"> <input class="text-widget required textline-field" id="form-widgets-subobject-widgets-moofield" name="form.widgets.subobject.widgets.moofield" type="text" value=""> </div> <input name="form.widgets.subobject-empty-marker" type="hidden" value="1"> </div> </div> <div class="row"> <label for="form-widgets-name">name</label> <input class="text-widget required textline-field" id="form-widgets-name" name="form.widgets.name" type="text" value=""> </div> <div class="action"> <input class="submit-widget button-field" id="form-buttons-add" name="form.buttons.add" type="submit" value="Add"> </div> </form> </body> </html> Coverage happiness ################## Converting interfaces.NO_VALUE holds None: >>> converter.toFieldValue(interfaces.NO_VALUE) is None True This is a complicated case. Happens when the context is a dict, and the dict misses the field. (Note, we're making ``sub__object`` instead of ``subobject``) >>> context = dict(sub__object=None, foo=123, bar=456) All the story the create a widget: >>> field = zope.schema.Object( ... __name__='subobject', ... title='my object widget', ... schema=IMySubObject) >>> wv = z3c.form.object.ObjectWidgetValue( ... {'foofield': '2', 'barfield': '999'}) >>> request = TestRequest() >>> widget = z3c.form.browser.object.ObjectWidget(request) >>> widget = FieldWidget(field, widget) >>> widget.context = context >>> widget.value = wv >>> widget.update() >>> converter = interfaces.IDataConverter(widget) And still we get a MySubObject, no failure: >>> value = converter.toFieldValue(wv) >>> value <z3c.form.testing.MySubObject object at ...> >>> value.foofield 2 >>> value.barfield 999 Easy (after the previous). In case the previous value on the context is None (or missing). We need to create a new object to be able to set properties on. >>> context['subobject'] = None >>> value = converter.toFieldValue(wv) >>> value <z3c.form.testing.MySubObject object at ...> >>> value.foofield 2 >>> value.barfield 999 In case there is something that cannot be adapted to the right interface, it just burps: (might be an idea to create in this case also a new blank object) >>> context['subobject'] = 'brutal' >>> converter.toFieldValue(wv) Traceback (most recent call last): ... TypeError: ('Could not adapt', 'brutal', z3c.form.testing.IMySubObject >>> context['subobject'] = None One more. Value to convert misses a field. Should never happen actually: >>> wv = z3c.form.object.ObjectWidgetValue( ... {'foofield': '2'}) >>> value = converter.toFieldValue(wv) Known property is set: >>> value.foofield 2 Unknown sticks ti it's default value: >>> value.barfield 2222
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/object.rst
object.rst
Checkbox Widget --------------- Note: the checkbox widget isn't registered for a field by default. You can use the ``widgetFactory`` argument of a ``IField`` object if you construct fields or set the custom widget factory on selected fields later. The ``CheckBoxWidget`` widget renders a checkbox input type field e.g. <input type="checkbox" /> >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import checkbox The ``CheckboxWidget`` is a widget: >>> verifyClass(interfaces.IWidget, checkbox.CheckBoxWidget) True The widget can render a input field only by adapting a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = checkbox.CheckBoxWidget(request) Set a name and id for the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Such a field provides IWidget: >>> interfaces.IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import z3c.form.browser >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'checkbox_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we only get the empty marker: >>> print(widget.render()) <input name="widget.name-empty-marker" type="hidden" value="1" /> Let's provide some values for this widget. We can do this by defining a vocabulary providing ``ITerms``. This vocabulary uses descriminators wich will fit for our setup. >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary >>> import z3c.form.term >>> class MyTerms(z3c.form.term.ChoiceTermsVocabulary): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary.fromValues(['yes', 'no']) >>> zope.component.provideAdapter(z3c.form.term.BoolTerms, ... adapts=(zope.interface.Interface, ... interfaces.IFormLayer, zope.interface.Interface, ... zope.interface.Interface, interfaces.ICheckBoxWidget)) Now let's try if we get widget values: >>> widget.update() >>> print(widget.render()) <span id="widget-id"> <span class="option"> <input type="checkbox" id="widget-id-0" name="widget.name:list" class="checkbox-widget" value="true" /> <label for="widget-id-0"> <span class="label">yes</span> </label> </span><span class="option"> <input type="checkbox" id="widget-id-1" name="widget.name:list" class="checkbox-widget" value="false" /> <label for="widget-id-1"> <span class="label">no</span> </label> </span> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The checkbox json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'checked': False, 'id': 'widget-id-0', 'label': 'yes', 'name': 'widget.name:list', 'value': 'true'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name:list', 'value': 'false'}], 'required': False, 'type': 'check', 'value': ()} If we set the value for the widget to ``yes``, we can se that the checkbox field get rendered with a checked flag: >>> widget.value = 'true' >>> widget.update() >>> print(widget.render()) <span id="widget-id"> <span class="option"> <input type="checkbox" id="widget-id-0" name="widget.name:list" class="checkbox-widget" value="true" checked="checked" /> <label for="widget-id-0"> <span class="label">yes</span> </label> </span><span class="option"> <input type="checkbox" id="widget-id-1" name="widget.name:list" class="checkbox-widget" value="false" /> <label for="widget-id-1"> <span class="label">no</span> </label> </span> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The checkbox json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'input', 'name': 'widget.name', 'options': [{'checked': True, 'id': 'widget-id-0', 'label': 'yes', 'name': 'widget.name:list', 'value': 'true'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name:list', 'value': 'false'}], 'required': False, 'type': 'check', 'value': 'true'} Check HIDDEN_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'checkbox_hidden.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden') >>> widget.value = 'true' >>> widget.mode = interfaces.HIDDEN_MODE >>> print(widget.render()) <span class="option"> <input type="hidden" id="widget-id-0" name="widget.name:list" class="checkbox-widget" value="true" /> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The checkbox json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': '', 'mode': 'hidden', 'name': 'widget.name', 'options': [{'checked': True, 'id': 'widget-id-0', 'label': 'yes', 'name': 'widget.name:list', 'value': 'true'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name:list', 'value': 'false'}], 'required': False, 'type': 'check', 'value': 'true'} Make sure that we produce a proper label when we have no title for a term and the value (which is used as a backup label) contains non-ASCII characters: >>> terms = SimpleVocabulary.fromValues([b'yes\012', b'no\243']) >>> widget.terms = terms >>> widget.update() >>> pprint(list(widget.items)) [{'checked': False, 'id': 'widget-id-0', 'label': 'yes\n', 'name': 'widget.name:list', 'value': 'yes\n'}, {'checked': False, 'id': 'widget-id-1', 'label': 'no', 'name': 'widget.name:list', 'value': 'no...'}] Note: The "\234" character is interpreted differently in Pytohn 2 and 3 here. (This is mostly due to changes int he SimpleVocabulary code.) Single Checkbox Widget ###################### Instead of using the checkbox widget as an UI component to allow multiple selection from a list of choices, it can be also used by itself to toggle a selection, effectively making it a binary selector. So in this case it lends itself well as a boolean UI input component. The ``SingleCheckboxWidget`` is a widget: >>> verifyClass(interfaces.IWidget, checkbox.SingleCheckBoxWidget) True The widget can render a input field only by adapting a request: >>> request = TestRequest() >>> widget = checkbox.SingleCheckBoxWidget(request) Set a name and id for the widget: >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' Such a widget provides the ``IWidget`` interface: >>> interfaces.IWidget.providedBy(widget) True For there to be a sensible output, we need to give the widget a label: >>> widget.label = u'Do you want that?' >>> widget.update() >>> print(widget.render()) <span class="option" id="widget-id"> <input type="checkbox" id="widget-id-0" name="widget.name:list" class="single-checkbox-widget" value="selected" /> <label for="widget-id-0"> <span class="label">Do you want that?</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> The checkbox json_data representation: >>> from pprint import pprint >>> pprint(widget.json_data()) {'error': '', 'id': 'widget-id', 'label': 'Do you want that?', 'mode': 'input', 'name': 'widget.name', 'options': [{'checked': False, 'id': 'widget-id-0', 'label': 'Do you want that?', 'name': 'widget.name:list', 'value': 'selected'}], 'required': False, 'type': 'check', 'value': ()} Initially, the box is not checked. Changing the widget value to the selection value, ... >>> widget.value = ['selected'] will make the box checked: >>> widget.update() >>> print(widget.render()) <span class="option" id="widget-id"> <input type="checkbox" id="widget-id-0" name="widget.name:list" class="single-checkbox-widget" value="selected" checked="checked" /> <label for="widget-id-0"> <span class="label">Do you want that?</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> If you do not specify the label on the widget directly, it is taken from the field >>> from zope.schema import Bool >>> widget = checkbox.SingleCheckBoxWidget(request) >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' >>> widget.field = Bool(title=u"Do you REALLY want that?") >>> widget.update() >>> print(widget.render()) <span class="option" id="widget-id"> <input type="checkbox" id="widget-id-0" name="widget.name:list" class="single-checkbox-widget" value="selected" /> <label for="widget-id-0"> <span class="label">Do you REALLY want that?</span> </label> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> Check HIDDEN_MODE: >>> template = os.path.join(os.path.dirname(z3c.form.browser.__file__), ... 'checkbox_hidden.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='hidden') >>> widget.value = 'selected' >>> widget.mode = interfaces.HIDDEN_MODE >>> print(widget.render()) <span class="option"> <input type="hidden" id="widget-id-0" name="widget.name:list" class="single-checkbox-widget" value="selected" /> </span> <input name="widget.name-empty-marker" type="hidden" value="1" /> Term with non ascii __str__ ########################### Check if a term which __str__ returns non ascii string does not crash the update method >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import checkbox >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = checkbox.CheckBoxWidget(request) >>> widget.id = 'widget-id' >>> widget.name = 'widget.name' >>> import zope.schema.interfaces >>> from zope.schema.vocabulary import SimpleVocabulary,SimpleTerm >>> import z3c.form.term >>> class ObjWithNonAscii__str__: ... def __str__(self): ... return 'héhé!' >>> class MyTerms(z3c.form.term.ChoiceTermsVocabulary): ... def __init__(self, context, request, form, field, widget): ... self.terms = SimpleVocabulary([ ... SimpleTerm(ObjWithNonAscii__str__(), 'one', 'One'), ... SimpleTerm(ObjWithNonAscii__str__(), 'two', 'Two'), ... ]) >>> zope.component.provideAdapter(MyTerms, ... adapts=(zope.interface.Interface, ... interfaces.IFormLayer, zope.interface.Interface, ... zope.interface.Interface, interfaces.ICheckBoxWidget)) >>> widget.update() >>> print(widget.render()) <html> <body> <span id="widget-id"> <span class="option"> <input class="checkbox-widget" id="widget-id-0" name="widget.name:list" type="checkbox" value="one"> <label for="widget-id-0"> <span class="label">One</span> </label> </span> <span class="option"> <input class="checkbox-widget" id="widget-id-1" name="widget.name:list" type="checkbox" value="two"> <label for="widget-id-1"> <span class="label">Two</span> </label> </span> </span> <input name="widget.name-empty-marker" type="hidden" value="1"> </body> </html>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/checkbox.rst
checkbox.rst
__docformat__ = "reStructuredText" from operator import attrgetter import zope.component import zope.interface from z3c.form import button from z3c.form import interfaces from z3c.form import widget from z3c.form.browser.widget import HTMLFormElement from z3c.form.i18n import MessageFactory as _ @zope.interface.implementer(interfaces.IButtonForm, interfaces.IHandlerForm) class FormMixin: pass @zope.interface.implementer(interfaces.IMultiWidget) class MultiWidget(HTMLFormElement, widget.MultiWidget, FormMixin): """Multi widget implementation.""" buttons = button.Buttons() prefix = 'widget' klass = 'multi-widget' css = 'multi' items = () showLabel = True # show labels for item subwidgets or not # Internal attributes _adapterValueAttributes = widget.MultiWidget._adapterValueAttributes + \ ('showLabel',) def updateActions(self): self.updateAllowAddRemove() if self.name is not None: self.prefix = self.name self.actions = zope.component.getMultiAdapter( (self, self.request, self), interfaces.IActions) self.actions.update() def update(self): """See z3c.form.interfaces.IWidget.""" super().update() self.updateActions() self.actions.execute() self.updateActions() # Update again, as conditions may change @button.buttonAndHandler(_('Add'), name='add', condition=attrgetter('allowAdding')) def handleAdd(self, action): self.appendAddingWidget() @button.buttonAndHandler(_('Remove selected'), name='remove', condition=attrgetter('allowRemoving')) def handleRemove(self, action): self.removeWidgets([widget.name for widget in self.widgets if ('%s.remove' % (widget.name)) in self.request]) @zope.interface.implementer(interfaces.IFieldWidget) def multiFieldWidgetFactory(field, request): """IFieldWidget factory for MultiWidget.""" return widget.FieldWidget(field, MultiWidget(request)) @zope.interface.implementer(interfaces.IFieldWidget) def MultiFieldWidget(field, value_type, request): """IFieldWidget factory for MultiWidget.""" return multiFieldWidgetFactory(field, request)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/multi.py
multi.py
TextLines Widget ---------------- The text lines widget allows you to store a sequence of textline. This sequence is stored as a list or tuple. This depends on what you are using as sequence type. As for all widgets, the text lines widget must provide the new ``IWidget`` interface: >>> from zope.interface.verify import verifyClass >>> from z3c.form import interfaces >>> from z3c.form.browser import textlines >>> verifyClass(interfaces.IWidget, textlines.TextLinesWidget) True The widget can be instantiated only using the request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = textlines.TextLinesWidget(request) Before rendering the widget, one has to set the name and id of the widget: >>> widget.id = 'id' >>> widget.name = 'name' We also need to register the template for at least the widget and request: >>> import zope.component >>> from zope.pagetemplate.interfaces import IPageTemplate >>> from z3c.form.testing import getPath >>> from z3c.form.widget import WidgetTemplateFactory >>> zope.component.provideAdapter( ... WidgetTemplateFactory(getPath('textlines_input.pt'), 'text/html'), ... (None, None, None, None, interfaces.ITextLinesWidget), ... IPageTemplate, name=interfaces.INPUT_MODE) If we render the widget we get an empty textarea widget: >>> print(widget.render()) <textarea id="id" name="name" class="textarea-widget"></textarea> Adding some more attributes to the widget will make it display more: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'foo\nbar' >>> print(widget.render()) <textarea id="id" name="name" class="textarea-widget">foo bar</textarea> TextLinesFieldWidget #################### The field widget needs a field: >>> import zope.schema >>> text = zope.schema.List( ... title=u'List', ... value_type=zope.schema.TextLine()) >>> widget = textlines.TextLinesFieldWidget(text, request) >>> widget <TextLinesWidget ''> >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'foo\nbar' >>> print(widget.render()) <textarea id="id" name="name" class="textarea-widget">foo bar</textarea> TextLinesFieldWidgetFactory ########################### >>> widget = textlines.TextLinesFieldWidgetFactory(text, text.value_type, ... request) >>> widget <TextLinesWidget ''> >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'foo\nbar' >>> print(widget.render()) <textarea id="id" name="name" class="textarea-widget">foo bar</textarea>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/textlines.rst
textlines.rst
ObjectWidget single widgets integration tests --------------------------------------------- Checking components on the highest possible level. >>> from datetime import date >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import testing >>> from z3c.form.object import registerFactoryAdapter >>> registerFactoryAdapter(testing.IObjectWidgetSingleSubIntegration, ... testing.ObjectWidgetSingleSubIntegration) >>> request = testing.TestRequest() >> from z3c.form.object import registerFactoryAdapter >> registerFactoryAdapter(testing.IObjectWidgetSingleSubIntegration, .. testing.ObjectWidgetSingleSubIntegration) >>> class EForm(form.EditForm): ... form.extends(form.EditForm) ... fields = field.Fields(testing.IObjectWidgetSingleIntegration) Our single content object: >>> obj = testing.ObjectWidgetSingleIntegration() We recreate the form each time, to stay as close as possible. In real life the form gets instantiated and destroyed with each request. >>> def getForm(request, fname=None): ... frm = EForm(obj, request) ... testing.addTemplate(frm, 'integration_edit.pt') ... frm.update() ... content = frm.render() ... if fname is not None: ... testing.saveHtml(content, fname) ... return content Empty ##### All blank and empty values: >>> content = getForm(request, 'ObjectWidget_single_edit_empty.html') >>> print(testing.plainText(content)) Object label Int label * [] Bool label * ( ) yes ( ) no Choice label * [[ ]] ChoiceOpt label [No value] TextLine label * [] Date label * [] ReadOnly label * [] [Apply] Some valid default values ######################### >>> obj.subobj = testing.ObjectWidgetSingleSubIntegration( ... singleInt=-100, ... singleBool=False, ... singleChoice='two', ... singleChoiceOpt='six', ... singleTextLine='some text one', ... singleDate=date(2014, 6, 20), ... singleReadOnly='some R/O text') >>> content = getForm(request, 'ObjectWidget_single_edit_simple.html') >>> print(testing.plainText(content)) Object label Int label * [-100] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] ReadOnly label * some R/O text [Apply] Wrong values ############ Set wrong values: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.subobj.widgets.singleInt'] = 'foobar' >>> submit['form.widgets.subobj.widgets.singleTextLine'] = 'foo\nbar' >>> submit['form.widgets.subobj.widgets.singleDate'] = 'foobar' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) We should get lots of errors: >>> content = getForm(request, 'ObjectWidget_single_edit_submit_wrong.html') >>> print(testing.plainText(content, ... './/ul[@id="form-errors"]')) * Object label: The entered value is not a valid integer literal. Constraint not satisfied The datetime string did not match the pattern 'yy/MM/dd'. >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-subobj"]/b/div[@class="error"]')) The entered value is not a valid integer literal. Constraint not satisfied The datetime string did not match the pattern 'yy/MM/dd'. >>> print(testing.plainText(content, ... './/div[@id="row-form-widgets-subobj"]')) The entered value is not a valid integer literal. Constraint not satisfied The datetime string did not match the pattern 'yy/MM/dd'. Object label Int label * <BLANKLINE> The entered value is not a valid integer literal. [foobar] <BLANKLINE> Bool label * <BLANKLINE> ( ) yes (O) no <BLANKLINE> Choice label * <BLANKLINE> [two] <BLANKLINE> ChoiceOpt label <BLANKLINE> [six] <BLANKLINE> TextLine label * <BLANKLINE> Constraint not satisfied [foo bar] <BLANKLINE> Date label * <BLANKLINE> The datetime string did not match the pattern 'yy/MM/dd'. [foobar] <BLANKLINE> ReadOnly label * <BLANKLINE> some R/O text Let's fix the values: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.subobj.widgets.singleInt'] = '1042' >>> submit['form.widgets.subobj.widgets.singleBool'] = 'true' >>> submit['form.widgets.subobj.widgets.singleChoice:list'] = 'three' >>> submit['form.widgets.subobj.widgets.singleChoiceOpt:list'] = 'four' >>> submit['form.widgets.subobj.widgets.singleTextLine'] = 'foobar' >>> submit['form.widgets.subobj.widgets.singleDate'] = '14/06/21' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectWidget_single_edit_submit_fixed.html') >>> print(testing.plainText(content)) Data successfully updated. <BLANKLINE> Object label Int label * [1,042] Bool label * (O) yes ( ) no Choice label * [three] ChoiceOpt label [four] TextLine label * [foobar] Date label * [14/06/21] ReadOnly label * some R/O text [Apply] Bool was misbehaving >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.subobj.widgets.singleBool'] = 'false' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectWidget_single_edit_submit_bool1.html') >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.subobj) <ObjectWidgetSingleSubIntegration singleBool: False singleChoice: 'three' singleChoiceOpt: 'four' singleDate: datetime.date(2014, 6, 21) singleInt: 1042 singleReadOnly: 'some R/O text' singleTextLine: 'foobar'> >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.subobj.widgets.singleBool'] = 'true' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectWidget_single_edit_submit_bool2.html') >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.subobj) <ObjectWidgetSingleSubIntegration singleBool: True singleChoice: 'three' singleChoiceOpt: 'four' singleDate: datetime.date(2014, 6, 21) singleInt: 1042 singleReadOnly: 'some R/O text' singleTextLine: 'foobar'>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/object_single_integration.rst
object_single_integration.rst
Widget base classes =================== HTMLFormElement --------------- The widget base class. :: >>> from z3c.form.browser.widget import HTMLFormElement >>> form = HTMLFormElement() addClass ........ Widgets based on :code:`HTMLFormElement` also have the :code:`addClass` method which can be used to add CSS classes to the widget. The :code:`klass` attribute is used because :code:`class` is a reserved keyword in Python. It's empty per default:: >>> form = HTMLFormElement() >>> form.klass After adding a class it shows up in :code:`klass`:: >>> form.addClass("my-css-class") >>> form.klass 'my-css-class' :code:`addClass` prevents adding the same class twice:: >>> form.addClass("my-css-class") >>> form.klass 'my-css-class' >>> form.addClass("another-class") >>> form.klass 'my-css-class another-class' >>> form.addClass("another-class third-class") >>> form.klass 'my-css-class another-class third-class' The duplicate removal also keeps the original order of CSS classes:: >>> form.addClass("third-class another-class") >>> form.klass 'my-css-class another-class third-class' attributes .......... On widgets you can programatically add, remove or modify HTML attributes:: >>> form = HTMLFormElement() >>> form.id = "my-input" >>> form.title = "This is my input." >>> form.attributes {'id': 'my-input', 'title': 'This is my input.'} Only attributes with values are included in :code:`attributes`:: >>> form = HTMLFormElement() >>> form.id = "my-input" >>> form.attributes {'id': 'my-input'} The :code:`klass` attibute of the :code:`HTMLFormElement` is changed to :code:`class`:: >>> form = HTMLFormElement() >>> form.klass = "class-a class-b" >>> form.attributes {'class': 'class-a class-b'} Once :code:`attributes` was accessed you cannot set the HTML attributes on the `HTMLFormElement` directly anymore:: >>> form = HTMLFormElement() >>> form.id = "my-input" >>> form.attributes {'id': 'my-input'} >>> form.id = "no-input" >>> form.title = "This is my input." >>> form.attributes {'id': 'my-input'} But you can change them via the :code:`attributes` property:: >>> form = HTMLFormElement() >>> form.id = "my-input" >>> form.attributes {'id': 'my-input'} >>> form.attributes["id"] = "no-input" >>> form.attributes["title"] = "Okay. No input then." >>> form.attributes {'id': 'no-input', 'title': 'Okay. No input then.'} >>> form.attributes.update({"title": "The no input input.", "class": "class-a"}) >>> form.attributes {'id': 'no-input', 'title': 'The no input input.', 'class': 'class-a'} You can delete items:: >>> del form.attributes["class"] >>> form.attributes {'id': 'no-input', 'title': 'The no input input.'} And directly set it anew:: >>> form.attributes = {'id': 'okay', 'title': 'I give up.'} >>> form.attributes {'id': 'okay', 'title': 'I give up.'} You can use attributes to render inputs in a generic way without explicitly including all the HTML attributes. Note: This only works if you use Chameleon templates. It does not work with the Zope PageTemplate reference implementation. This is how you would write your Chameleon template:: <input type="text" tal:attributes="view/attributes" />
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/widget.rst
widget.rst
ObjectWidget integration with MultiWidget of dict ------------------------------------------------- a.k.a. dict of objects widget >>> from datetime import date >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.form import testing >>> from z3c.form.object import registerFactoryAdapter >>> registerFactoryAdapter(testing.IObjectWidgetMultiSubIntegration, ... testing.ObjectWidgetMultiSubIntegration) >>> request = testing.TestRequest() >>> class EForm(form.EditForm): ... form.extends(form.EditForm) ... fields = field.Fields( ... testing.IMultiWidgetDictIntegration).select('dictOfObject') Our multi content object: >>> obj = testing.MultiWidgetDictIntegration() We recreate the form each time, to stay as close as possible. In real life the form gets instantiated and destroyed with each request. >>> def getForm(request, fname=None): ... frm = EForm(obj, request) ... testing.addTemplate(frm, 'integration_edit.pt') ... frm.update() ... content = frm.render() ... if fname is not None: ... testing.saveHtml(content, fname) ... return content Empty ##### All blank and empty values: >>> content = getForm(request, 'ObjectMulti_dict_edit_empty.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> [Add] [Apply] Some valid default values ######################### >>> sub1 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=-100, ... multiBool=False, ... multiChoice='two', ... multiChoiceOpt='six', ... multiTextLine='some text one', ... multiDate=date(2014, 6, 20)) >>> sub2 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=42, ... multiBool=True, ... multiChoice='one', ... multiChoiceOpt='four', ... multiTextLine='second txt', ... multiDate=date(2011, 3, 15)) >>> obj.dictOfObject = {'subob1': sub1, 'subob2': sub2} >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} >>> content = getForm(request, 'ObjectMulti_dict_edit_simple.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * [ ] Int label * [-100] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] Object key * [subob2] Object label * [ ] Int label * [42] Bool label * (O) yes ( ) no Choice label * [one] ChoiceOpt label [four] TextLine label * [second txt] Date label * [11/03/15] [Add] [Remove selected] [Apply] wrong input (Int) ################# Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiInt'] = 'foobar' >>> submit['form.widgets.dictOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The entered value is not a valid integer literal." for "foobar" and a new input. >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_int.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-0-row"]')) Object key * <BLANKLINE> [subob1] <BLANKLINE> Object label * <BLANKLINE> The entered value is not a valid integer literal. <BLANKLINE> [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_int_again.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-0-row"]//div[@class="error"]')) Required input is missing. An object failed schema or invariant validation. Required input is missing. Required input is missing. Required input is missing. Required input is missing. >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-1-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-0-row"]')) Object key * <BLANKLINE> Required input is missing. <BLANKLINE> [] <BLANKLINE> Object label * <BLANKLINE> An object failed schema or invariant validation. <BLANKLINE> [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * Required input is missing. [] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.remove'] = '1' >>> submit['form.widgets.dictOfObject.2.remove'] = '1' >>> submit['form.widgets.dictOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_remove_int.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [some text one] Date label * [14/06/20] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} wrong input (TextLine) ###################### Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiTextLine'] = 'foo\nbar' >>> submit['form.widgets.dictOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "Constraint not satisfied" for "foo\nbar" and a new input. >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_textline.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-0-row"]')) Object key * <BLANKLINE> [subob1] <BLANKLINE> Object label * <BLANKLINE> The entered value is not a valid integer literal. <BLANKLINE> [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * [14/06/20] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_textline_again.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-0-row"]//div[@class="error"]')) Required input is missing. An object failed schema or invariant validation. Required input is missing. Required input is missing. Required input is missing. Required input is missing. >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-1-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. Constraint not satisfied Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.remove'] = '1' >>> submit['form.widgets.dictOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_remove_textline.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * [14/06/20] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} wrong input (Date) ################## Set a wrong value and add a new input: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiDate'] = 'foobar' >>> submit['form.widgets.dictOfObject.buttons.add'] = 'Add' >>> request = testing.TestRequest(form=submit) Important is that we get "The datetime string did not match the pattern" for "foobar" and a new input. >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_date.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] Object key * [] Object label * [ ] Int label * [] Bool label * ( ) yes ( ) no Choice label * [[ ]] ChoiceOpt label [No value] TextLine label * [] Date label * [] [Add] [Remove selected] [Apply] Submit again with the empty field: >>> submit = testing.getSubmitValues(content) >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_date_again.html') >>> print(testing.plainText(content, ... './/div[@id="form-widgets-dictOfObject-1-row"]//div[@class="error"]')) The entered value is not a valid integer literal. The entered value is not a valid integer literal. Constraint not satisfied The datetime string did not match the pattern 'yy/MM/dd'. Fill in a valid value: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiDate'] = '14/06/21' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_submit_date2.html') >>> print(testing.plainText(content)) DictOfObject label Object key * Required input is missing. [] Object label * An object failed schema or invariant validation. [ ] Int label * Required input is missing. [] Bool label * Required input is missing. ( ) yes ( ) no Choice label * [one] ChoiceOpt label [No value] TextLine label * Required input is missing. [] Date label * [14/06/21] Object key * [subob1] Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] [Add] [Remove selected] [Apply] Let's remove some items: >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.remove'] = '1' >>> submit['form.widgets.dictOfObject.buttons.remove'] = 'Remove selected' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_remove_date.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * The entered value is not a valid integer literal. [ ] Int label * The entered value is not a valid integer literal. [foobar] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * Constraint not satisfied [foo bar] Date label * The datetime string did not match the pattern 'yy/MM/dd'. [foobar] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} Fix values ########## >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiInt'] = '1042' >>> submit['form.widgets.dictOfObject.0.widgets.multiTextLine'] = 'moo900' >>> submit['form.widgets.dictOfObject.0.widgets.multiDate'] = '14/06/23' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_fix_values.html') >>> print(testing.plainText(content)) DictOfObject label <BLANKLINE> Object key * [subob1] Object label * [ ] Int label * [1,042] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [moo900] Date label * [14/06/23] [Add] [Remove selected] [Apply] The object is unchanged: >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} And apply >>> submit = testing.getSubmitValues(content) >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. <BLANKLINE> DictOfObject label <BLANKLINE> Object key * [subob1] Object label * [ ] Int label * [1,042] Bool label * ( ) yes (O) no Choice label * [two] ChoiceOpt label [six] TextLine label * [moo900] Date label * [14/06/23] [Add] [Remove selected] [Apply] Now the object gets updated: >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 23) multiInt: 1042 multiTextLine: 'moo900'>} Twisting some keys ################## Change key values, item values must stick to the new values. >>> sub1 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=-100, ... multiBool=False, ... multiChoice='two', ... multiChoiceOpt='six', ... multiTextLine='some text one', ... multiDate=date(2014, 6, 20)) >>> sub2 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=42, ... multiBool=True, ... multiChoice='one', ... multiChoiceOpt='four', ... multiTextLine='second txt', ... multiDate=date(2011, 3, 15)) >>> obj.dictOfObject = {'subob1': sub1, 'subob2': sub2} >>> request = testing.TestRequest() >>> content = getForm(request, 'ObjectMulti_dict_edit_twist.html') >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.key.0'] = 'twisted' # was subob1 >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_twist2.html') >>> pprint(obj.dictOfObject) {'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>, 'twisted': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>} >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.key.1'] = 'subob2' # was twisted >>> submit['form.widgets.dictOfObject.key.0'] = 'subob1' # was subob2 >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request, 'ObjectMulti_dict_edit_twist2.html') >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>} Bool was misbehaving #################### >>> sub1 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=-100, ... multiBool=False, ... multiChoice='two', ... multiChoiceOpt='six', ... multiTextLine='some text one', ... multiDate=date(2014, 6, 20)) >>> sub2 = testing.ObjectWidgetMultiSubIntegration( ... multiInt=42, ... multiBool=True, ... multiChoice='one', ... multiChoiceOpt='four', ... multiTextLine='second txt', ... multiDate=date(2011, 3, 15)) >>> obj.dictOfObject = {'subob1': sub1, 'subob2': sub2} >>> request = testing.TestRequest() >>> content = getForm(request) >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiBool'] = 'true' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>} >>> submit = testing.getSubmitValues(content) >>> submit['form.widgets.dictOfObject.0.widgets.multiBool'] = 'false' >>> submit['form.buttons.apply'] = 'Apply' >>> request = testing.TestRequest(form=submit) >>> content = getForm(request) >>> print(testing.plainText(content)) Data successfully updated. ... >>> pprint(obj.dictOfObject) {'subob1': <ObjectWidgetMultiSubIntegration multiBool: False multiChoice: 'two' multiChoiceOpt: 'six' multiDate: datetime.date(2014, 6, 20) multiInt: -100 multiTextLine: 'some text one'>, 'subob2': <ObjectWidgetMultiSubIntegration multiBool: True multiChoice: 'one' multiChoiceOpt: 'four' multiDate: datetime.date(2011, 3, 15) multiInt: 42 multiTextLine: 'second txt'>}
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/object_multi_dict_integration.rst
object_multi_dict_integration.rst
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema import zope.schema.interfaces from zope.i18n import translate from z3c.form import interfaces from z3c.form.browser import widget from z3c.form.widget import FieldWidget from z3c.form.widget import SequenceWidget @zope.interface.implementer_only(interfaces.IOrderedSelectWidget) class OrderedSelectWidget(widget.HTMLSelectWidget, SequenceWidget): """Ordered-Select widget implementation.""" size = 5 multiple = 'multiple' items = () selectedItems = () notselectedItems = () def getItem(self, term, count=0): id = '%s-%i' % (self.id, count) content = term.value if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) return {'id': id, 'value': term.token, 'content': content} def update(self): """See z3c.form.interfaces.IWidget.""" super().update() widget.addFieldClass(self) self.items = [ self.getItem(term, count) for count, term in enumerate(self.terms)] self.selectedItems = [ self.getItem(self.terms.getTermByToken(token), count) for count, token in enumerate(self.value)] self.notselectedItems = self.deselect() def deselect(self): selecteditems = [] notselecteditems = [] for selecteditem in self.selectedItems: selecteditems.append(selecteditem['value']) for item in self.items: if item['value'] not in selecteditems: notselecteditems.append(item) return notselecteditems def json_data(self): data = super().json_data() data['options'] = self.items data['selected'] = self.selectedItems data['notSelected'] = self.notselectedItems data['type'] = 'multiSelect' return data @zope.component.adapter(zope.schema.interfaces.ISequence, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def OrderedSelectFieldWidget(field, request): """IFieldWidget factory for SelectWidget.""" return FieldWidget(field, OrderedSelectWidget(request)) @zope.component.adapter( zope.schema.interfaces.ISequence, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def SequenceSelectFieldWidget(field, request): """IFieldWidget factory for SelectWidget.""" return zope.component.getMultiAdapter( (field, field.value_type, request), interfaces.IFieldWidget) @zope.interface.implementer(interfaces.IFieldWidget) def SequenceChoiceSelectFieldWidget(field, value_type, request): """IFieldWidget factory for SelectWidget.""" return OrderedSelectFieldWidget(field, request)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/orderedselect.py
orderedselect.py
Customizing widget lookup for IChoice ------------------------------------- Widgets for fields implementing IChoice are looked up not only according to the field, but also according to the source used by the field. >>> import z3c.form.testing >>> import zope.interface >>> import zope.component >>> from z3c.form import interfaces >>> from z3c.form.testing import TestRequest >>> z3c.form.testing.setupFormDefaults() >>> def setupWidget(field): ... request = TestRequest() ... widget = zope.component.getMultiAdapter((field, request), ... interfaces.IFieldWidget) ... widget.id = 'foo' ... widget.name = 'bar' ... return widget We define a sample field and source: >>> from zope.schema import vocabulary >>> terms = [vocabulary.SimpleTerm(*value) for value in ... [(True, 'yes', 'Yes'), (False, 'no', 'No')]] >>> vocabulary = vocabulary.SimpleVocabulary(terms) >>> field = zope.schema.Choice(default=True, vocabulary=vocabulary) The default widget is the SelectWidget: >>> widget = setupWidget(field) >>> type(widget) <class 'z3c.form.browser.select.SelectWidget'> But now we define a marker interface and have our source provide it: >>> from z3c.form.widget import FieldWidget >>> class ISampleSource(zope.interface.Interface): ... pass >>> zope.interface.alsoProvides(vocabulary, ISampleSource) We can then create and register a special widget for fields using sources with the ISampleSource marker: >>> class SampleSelectWidget(z3c.form.browser.select.SelectWidget): ... pass >>> def SampleSelectFieldWidget(field, source, request): ... return FieldWidget(field, SampleSelectWidget(request)) >>> zope.component.provideAdapter( ... SampleSelectFieldWidget, ... (zope.schema.interfaces.IChoice, ISampleSource, interfaces.IFormLayer), ... interfaces.IFieldWidget) If we now look up the widget for the field, we get the specialized widget: >>> widget = setupWidget(field) >>> type(widget) <class 'SampleSelectWidget'> Backwards compatibility ####################### To maintain backwards compatibility, SelectFieldWidget() still can be called without passing a source: >>> import z3c.form.browser.select >>> request = TestRequest() >>> widget = z3c.form.browser.select.SelectFieldWidget(field, request) >>> type(widget) <class 'z3c.form.browser.select.SelectWidget'>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/browser/select-source.rst
select-source.rst
.. include:: ../README.rst The documents are ordered in the way they should be read: .. toctree:: :maxdepth: 2 mustread/index advanced/index informative/index widgets/index ================= API Documentation ================= .. toctree:: :maxdepth: 2 interfaces =========== Development =========== .. toctree:: :maxdepth: 1 changelog authors todos ================== Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/docs/index.rst
index.rst
Must read ========= .. toctree:: :numbered: :maxdepth: 1 Forms - Setup and usage of forms including structure of form components <form> Group Forms - Implementation and usage of widget groups <group> Sub-Forms - Introduction into sub-forms and the implemented two classes of thereof <subform> field Buttons - Button manager API, creation of buttons within schemas and conversion to actions <button> ZCML Directives - Register new templates without writing Python code <zcml>
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/docs/mustread/index.rst
index.rst
===================================================== Demo Applications for ``z3c.form`` and ``z3c.formui`` ===================================================== This package contains several small demo applications for the ``z3c.form`` and ``z3c.formui`` packages. * TABLE- versus DIV-based layout of all widgets. * A simple Hello World message application demonstrating the easiest way to write add, edit and display forms. * A simple calculator showing the flexibility of the new action declaration framework by declaring different classes of buttons. * A linear wizard shows off the sub-form capabilities of z3c.form. It also demonstrates how one can overcome the short-coming of an object widget. * A simple table/spreadsheet that allows adding and editing as simple content object. This demo also shows the usage of forms and ``zc.table`` at the same time. Running the Demo out of the box ------------------------------- You can also run the demo directly without manually installing Zope 3:: $ svn co svn://svn.zope.org/repos/main/z3c.formdemo/trunk formdemo $ cd formdemo $ python bootstrap.py $ ./bin/buildout $ ./bin/demo fg Then access the demo site using: http://localhost:8080/
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/README.txt
README.txt
====== README ====== This package provides different sample for the z3c.form and z3c.formui packages. If you run the Zope3 server at port 8080, you can access the different demos with two skins. The Z3CFormDemo skin uses the div based form layout and is accessible via: http://localhost:8080/++skin++Z3CFormDemo/ and the Z3CTableFormDemo skin uses the table based form layout and is accessible via: http://localhost:8080/++skin++Z3CFormDemo/. Both skin offer a index.html page with a list of demo pages.
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/README.txt
README.txt
__docformat__ = "reStructuredText" import decimal import zope.interface from zope.session.interfaces import ISession from zope.viewlet.viewlet import CSSViewlet from z3c.form import button, form, interfaces from z3c.formui import layout SESSION_KEY = 'z3c.formdemo.calculator' CalculatorCSSViewlet = CSSViewlet('calculator.css') class SessionProperty(object): def __init__(self, name, default=None): self.name = name self.default = default def __get__(self, inst, klass): session = ISession(inst.request)[SESSION_KEY] return session.get(self.name, self.default) def __set__(self, inst, value): session = ISession(inst.request)[SESSION_KEY] session[self.name] = value class IGridButton(interfaces.IButton): """A button within the grid.""" class Literal(button.Button): zope.interface.implements(IGridButton) def __init__(self, *args, **kwargs): literal = kwargs.pop('literal', None) super(Literal, self).__init__(*args, **kwargs) if literal is None: self.literal = self.title else: self.literal = literal self.accessKey = self.literal class Operator(button.Button): zope.interface.implements(IGridButton) operation = None def __init__(self, *args, **kwargs): self.operation = kwargs.pop('operation', None) kwargs['accessKey'] = kwargs['title'] super(Operator, self).__init__(*args, **kwargs) def operate(self, x, y): return getattr(x, self.operation)(y) class GridButtonActions(button.ButtonActions): cols = 4 def grid(self): rows = [] current = [] for button in self.values(): if not IGridButton.providedBy(button.field): continue current.append(button) if len(current) == self.cols: rows.append(current) current = [] if current: current += [None]*(self.cols-len(current)) rows.append(current) return rows class Calculator(layout.FormLayoutSupport, form.Form): buttons = button.Buttons( Literal('one', title=u'1'), Literal('two', title=u'2'), Literal('three', title=u'3'), Operator('add', title=u'+', operation='__add__'), Literal('four', title=u'4'), Literal('five', title=u'5'), Literal('six', title=u'6'), Operator('sub', title=u'-', operation='__sub__'), Literal('seven', title=u'7'), Literal('eight', title=u'8'), Literal('nine', title=u'9'), Operator('mul', title=u'*', operation='__mul__'), Literal('zero', title=u'0'), Literal('dec', title=u'.'), Operator('eq', title=u'='), Operator('div', title=u'/', operation='__div__'), button.Button('clear', title=u'C', accessKey=u"c"), ) stack = SessionProperty('stack', decimal.Decimal(0)) operator = SessionProperty('operator') current = SessionProperty('current', u'') maxSize = 12 def updateActions(self): self.actions = GridButtonActions(self, self.request, self.context) self.actions.update() @button.handler(Literal) def handleLiteral(self, action): if len(self.current) < self.maxSize: self.current += action.field.literal if self.operator is None: self.stack = decimal.Decimal(0) @button.handler(Operator) def handleOperator(self, action): try: current = decimal.Decimal(self.current) except decimal.DecimalException: current = decimal.Decimal(0) if self.operator is not None: try: self.stack = self.operator.operate(self.stack, current) except decimal.DecimalException, err: self.current = u'-E-' return err else: self.stack = current self.current = u'' self.operator = action.field @button.handler(buttons['eq']) def handleEqual(self, action): error = self.handleOperator(self, action) if not error: self.operator = None self.current = str(self.stack) @button.handler(buttons['clear']) def handleClear(self, action): self.operator = None self.stack = decimal.Decimal(0) self.current = u''
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/calculator/browser.py
browser.py
=============== Calculator Demo =============== The purpose of the calculator demo is demonstrate the concept of buttons and their actions and how the framework allows high degrees of customization. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "Calculator" link: >>> user.getLink('Calculator').click() You are now seeing the calculator: >>> testing.printElement(user, "//h1") <h1> <span class="name">A simple calculator</span> <span class="version">v1.0</span> </h1> Let's start by doing a simple addition (``35 + 4.3 = ``: >>> user.getControl('3').click() >>> user.getControl('5').click() >>> user.getControl('+').click() >>> user.getControl('4').click() >>> user.getControl('.').click() >>> user.getControl('3').click() >>> user.getControl('=').click() The result is shown within the display structure: >>> testing.printElement( ... user, "//div[@id='current']/span[@class='value']/text()", ... serialize=False) 39.3 When an illegal operation occurs, an error message is shown: >>> user.getControl('/').click() >>> user.getControl('0').click() >>> user.getControl('=').click() >>> testing.printElement( ... user, "//div[@id='current']/span[@class='value']/text()", ... serialize=False) -E- The entire calculator state can be reset at any time using the clear button: >>> user.getControl('C').click() >>> testing.printElement( ... user, "//div[@id='current']/span[@class='value']/text()", ... serialize=False) 0 If a non-valid number is entered, it is just replaced by zero: >>> user.getControl('4').click() >>> user.getControl('.').click() >>> user.getControl('.').click() >>> user.getControl('3').click() >>> user.getControl('=').click() >>> testing.printElement( ... user, "//div[@id='current']/span[@class='value']/text()", ... serialize=False) 0
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/calculator/README.txt
README.txt
__docformat__ = "reStructuredText" import zope.component import zope.interface from zope.session.interfaces import ISession from zope.viewlet.viewlet import CSSViewlet from z3c.form import button, field, form, subform from z3c.form.interfaces import IWidgets, IDataManager from z3c.formui import layout from z3c.formdemo.wizard import interfaces WizardCSSViewlet = CSSViewlet('wizard.css') class IWizardButtons(zope.interface.Interface): previous = button.Button( title=u'Previous', condition=lambda form: not form.isFirstStep()) zope.interface.alsoProvides( previous, (interfaces.ISaveButton, interfaces.IBackButton)) save = button.Button( title=u'Save') zope.interface.alsoProvides( save, (interfaces.ISaveButton, interfaces.IForwardButton)) next = button.Button( title=u'Next', condition=lambda form: not form.isLastStep()) zope.interface.alsoProvides( next, (interfaces.ISaveButton, interfaces.IForwardButton)) finish = button.Button( title=u'Finish', condition=lambda form: form.isLastStep() and form.isComplete()) zope.interface.alsoProvides( finish, (interfaces.ISaveButton, interfaces.IForwardButton)) class Step(subform.EditSubForm): zope.interface.implements(interfaces.IStep) name = None label = None def isComplete(self): """See interfaces.IStep This implementation checks that all required fields have been filled out. """ content = self.getContent() for field in self.fields.values(): if not field.field.required: continue dm = zope.component.getMultiAdapter( (content, field.field), IDataManager) if dm.get() is field.field.missing_value: return False return True @button.handler(interfaces.ISaveButton) def handleAllButtons(self, action): self.handleApply(self, action) class WizardButtonActions(button.ButtonActions): @property def backActions(self): return [action for action in self.values() if interfaces.IBackButton.providedBy(action.field)] @property def forwardActions(self): return [action for action in self.values() if interfaces.IForwardButton.providedBy(action.field)] class Wizard(layout.FormLayoutSupport, form.Form): zope.interface.implements(interfaces.IWizard) sessionKey = 'z3c.formdemo.wizard' buttons = button.Buttons(IWizardButtons) title = u'Wizard' steps = None step = None def isComplete(self): for name, StepClass in self.steps: step = StepClass(self.getContent(), self.request, self) if not step.isComplete(): return False return True def getCurrentStep(self): """See interfaces.IWizard""" session = ISession(self.request)[self.sessionKey] if 'step' in self.request: name = self.request['step'] step = name, dict(self.steps).get(name) else: step = session.get('step', self.steps[0]) session['step'] = step name, klass = step inst = klass(self.getContent(), self.request, self) inst.name = name return inst def isFirstStep(self): """See interfaces.IWizard""" return isinstance(self.step, self.steps[0][1]) def isLastStep(self): """See interfaces.IWizard""" return isinstance(self.step, self.steps[-1][1]) @property def stepsInfo(self): info = [] for pos, (name, step) in enumerate(self.steps): info.append({ 'name': name, 'number': str(pos+1), 'active': isinstance(self.step, step), 'class': isinstance(self.step, step) and 'active' or 'inactive' }) return info def updateActions(self): self.actions = WizardButtonActions(self, self.request, self.context) self.actions.update() def update(self): self.step = self.getCurrentStep() self.updateActions() self.step.update() self.actions.execute() super(Wizard, self).update() def finish(self): return NotImplementedError @button.handler(IWizardButtons['previous']) def handlePrevious(self, action): if self.step.widgets.errors: return for pos, (name, step) in enumerate(self.steps): if self.step.name == name: break url = self.request.getURL() + '?step=' + self.steps[pos-1][0] self.request.response.redirect(url) @button.handler(IWizardButtons['next']) def handleNext(self, action): if self.step.widgets.errors: return for pos, (name, step) in enumerate(self.steps): if self.step.name == name: break url = self.request.getURL() + '?step=' + self.steps[pos+1][0] self.request.response.redirect(url) @button.handler(IWizardButtons['save']) def handleSave(self, action): # Saving can change the conditions for the finish button, so we need # to reconstruct the button actions, since we do not redirect. self.updateActions() @button.handler(IWizardButtons['finish']) def handleFinish(self, action): session = ISession(self.request)[self.sessionKey] try: del session['step'] except KeyError: pass self.finish()
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/wizard/wizard.py
wizard.py
__docformat__ = "reStructuredText" import zope.interface import zope.schema from z3c.form import interfaces # ----[ Wizard Interfaces ]--------------------------------------------------- class ISaveButton(interfaces.IButton): """A button that causes the step data to be saved.""" class IBackButton(interfaces.IButton): """A button that returns to some previous state or screen.""" class IForwardButton(interfaces.IButton): """A button that returns to some next state or screen.""" class IStep(zope.interface.Interface): """An interface marking a step sub-form.""" def isComplete(): """Determines whether a step is complete.""" class IWizard(zope.interface.Interface): """An interface marking the controlling wizard form.""" def isComplete(): """Determines whether the wizard is complete.""" def getCurrentStep(): """Return the current step as an instance.""" def isFirstStep(): """Determine whether the current step is the first one.""" def isLastStep(): """Determine whether the current step is the last one.""" # ----[ Content Interfaces ]-------------------------------------------------- class IAddress(zope.interface.Interface): street = zope.schema.TextLine( title=u'Street', description=u'The street address.', default=u'', missing_value=u'', required=True) zip = zope.schema.TextLine( title=u'Zip', description=u'The zip code of the location.', default=u'', missing_value=u'', required=True) city = zope.schema.TextLine( title=u'City', description=u'The city.', default=u'', missing_value=u'', required=True) class IPersonalInfo(IAddress): lastName = zope.schema.TextLine( title=u'Last Name', description=u'The last name of the person.', default=u'', missing_value=u'', required=True) firstName = zope.schema.TextLine( title=u'First Name', description=u'The first name of the person.', default=u'', missing_value=u'', required=True) phone = zope.schema.TextLine( title=u'Phone', description=u'The phone number.', default=u'', missing_value=u'', required=False) email = zope.schema.TextLine( title=u'Email', description=u'The email address.', required=False) class IEmployerInfo(IAddress): name = zope.schema.TextLine( title=u'Name', description=u'The name of the employer.', default=u'', missing_value=u'', required=True) class IPerson(IPersonalInfo): father = zope.schema.Object( title=u'Father', description=u"Father's personal info.", schema=IPersonalInfo, required=True) mother = zope.schema.Object( title=u'Mother', description=u"Mother's personal info.", schema=IPersonalInfo, required=True) employer = zope.schema.Object( title=u'Employer', description=u"Employer's info.", schema=IEmployerInfo, required=True)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/wizard/interfaces.py
interfaces.py
__docformat__ = "reStructuredText" from zope.session.interfaces import ISession from z3c.form import button, field, form from z3c.formdemo.wizard import content, interfaces, wizard from z3c.formui import layout infoSelection = ( 'firstName', 'lastName', 'phone', 'email', 'street', 'city', 'zip') class PersonalInfoStep(wizard.Step): label = u'Personal Information' fields = field.Fields(interfaces.IPersonalInfo).select( 'firstName', 'lastName', 'phone', 'email') class AddressStep(wizard.Step): label = u'Address' fields = field.Fields(interfaces.IAddress) class FatherStep(wizard.Step): label = u'Father' fields = field.Fields(interfaces.IPersonalInfo).select(*infoSelection) def getContent(self): return self.context.father class MotherStep(wizard.Step): label = u'Mother' fields = field.Fields(interfaces.IPersonalInfo).select(*infoSelection) def getContent(self): return self.context.mother class EmployerStep(wizard.Step): label = u'Employer' fields = field.Fields(interfaces.IEmployerInfo).select( 'name', 'street', 'city', 'zip') def getContent(self): return self.context.employer class PersonWizard(wizard.Wizard): form.extends(wizard.Wizard) title = u'Wizard Demo - Person Demographics' sessionKey = 'z3c.formdemo.wizard.person' steps = [ ('personalInfo', PersonalInfoStep), ('address', AddressStep), ('father', FatherStep), ('mother', MotherStep), ('employer', EmployerStep)] def finish(self): self.request.response.redirect('summary.html') def getContent(self): session = ISession(self.request)[self.sessionKey] obj = session.get('content') if obj is None: obj = session['content'] = content.Person() return obj @button.buttonAndHandler( u'Clear', condition=lambda form: form.isFirstStep(), provides=(interfaces.IBackButton,)) def handleClear(self, action): session = ISession(self.request)[self.sessionKey] del session['content'] self.request.response.redirect( self.request.getURL() + '?step=' + self.steps[0][0]) class PersonSummary(layout.FormLayoutSupport, form.DisplayForm): fields = field.Fields(interfaces.IPersonalInfo).select(*infoSelection) def getContent(self): session = ISession(self.request)[PersonWizard.sessionKey] return session.get('content') def update(self): content = self.getContent() self.father = form.DisplayForm(content.father, self.request) self.father.fields = field.Fields(interfaces.IPersonalInfo).select( *infoSelection) self.father.update() self.mother = form.DisplayForm(content.mother, self.request) self.mother.fields = field.Fields(interfaces.IPersonalInfo).select( *infoSelection) self.mother.update() self.employer = form.DisplayForm(content.employer, self.request) self.employer.fields = field.Fields(interfaces.IEmployerInfo).select( 'name', 'street', 'city', 'zip') self.employer.update() super(PersonSummary, self).update()
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/wizard/browser.py
browser.py
=========== Wizard Demo =========== The purpose of the wizard demo is demonstrate the construction of a typical UI wizard, effectively splitting one form into multiple pages. None of the data is permanently stored until the wizard is submitted. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "Wizard" link: >>> user.getLink('Wizard').click() You are now seeing the first step of the wizard, which asks for personal information: >>> testing.printElement(user, "//h1") <h1>Wizard Demo - Person Demographics</h1> >>> testing.printElement(user, "//legend") <legend>Personal Information</legend> Let's fill out the form and save the data: >>> user.getControl('First Name').value = 'Stephan' >>> user.getControl('Last Name').value = 'Richter' >>> user.getControl('Phone').value = '+1 555 276-3761' >>> user.getControl('Email').value = 'stephan.richter_(at)_gmail.com' >>> user.getControl('Save').click() Rhe "Save" button causes the form to be submitted, but not to proceed to the next step. A message that the data has been successfully saved in shown: >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Data successfully updated.</div> Pressing the "Clear" button (which only appears on the first step) will clear out the data of all steps: >>> user.getControl('Clear').click() >>> user.getControl('First Name').value '' >>> user.getControl('Last Name').value '' >>> user.getControl('Phone').value '' >>> user.getControl('Email').value '' So let's now fill out the form and click the next button this time. >>> user.getControl('First Name').value = 'Stephan' >>> user.getControl('Phone').value = '+1 555 276-3761' >>> user.getControl('Email').value = 'stephan.richter_(at)_gmail.com' >>> user.getControl('Next').click() But we forgot the last name, which means the form does nto successfully submit and an error message is shown. So we are still at step 1: >>> testing.printElement(user, "//legend") <legend>Personal Information</legend> Filling in the missing required field will allow the action to be successful: >>> user.getControl('Last Name').value = 'Richter' >>> user.getControl('Next').click() You are now forwarded to the second step: >>> testing.printElement(user, "//legend") <legend>Address</legend> The "Next" button does not only forward the user to the second step, but also stores the data. Clicking on "Previous" will bring us back to the first screen. But let's first fill out step 2, since the "Previous" button also stores the data of the current step: >>> user.getControl('Street').value = '110 Main Street' >>> user.getControl('Zip').value = '01754' >>> user.getControl('Previous').click() But forgetting a required field does not get you to the previous step. >>> testing.printElement(user, "//legend") <legend>Address</legend> Filling out all information causes the action to be successful: >>> user.getControl('City').value = 'Maynard' >>> user.getControl('Previous').click() So back at step 1, we can see that all the personal information is there. >>> user.getControl('First Name').value 'Stephan' >>> user.getControl('Last Name').value 'Richter' >>> user.getControl('Phone').value '+1 555 276-3761' >>> user.getControl('Email').value 'stephan.richter_(at)_gmail.com' You can also navigate through the wizard by clicking on the step number on the top, so let's go to step 2 by clicking on that link: >>> user.getLink('2').click() >>> testing.printElement(user, "//legend") <legend>Address</legend> Note that no data is saved, when using this link. We also notice that all the data fields are filled out: >>> user.getControl('Street').value '110 Main Street' >>> user.getControl('Zip').value '01754' >>> user.getControl('City').value 'Maynard' Let's now go to the third and forth step, filling them out. >>> user.getControl('Next').click() >>> user.getControl('First Name').value = 'Wolfgang' >>> user.getControl('Last Name').value = 'Richter' >>> user.getControl('Phone').value = '+49 33 1271568' >>> user.getControl('Email').value = '[email protected]' >>> user.getControl('Street').value = u'Dorfstraße 12'.encode('utf-8') >>> user.getControl('Zip').value = '01945' >>> user.getControl('City').value = 'Tetta' >>> user.getControl('Next').click() >>> user.getControl('First Name').value = 'Marion' >>> user.getControl('Last Name').value = 'Richter' >>> user.getControl('Phone').value = '+49 33 1271568' >>> user.getControl('Street').value = u'Dorfstraße 12'.encode('utf-8') >>> user.getControl('Zip').value = '01945' >>> user.getControl('City').value = 'Tettau' >>> user.getControl('Next').click() We are now at the final screen. As you will notice, initially there is no button that allows submitting the wizard: >>> user.getControl('Finish') Traceback (most recent call last): ... LookupError: label 'Finish' This is because not all required fields have been filled out. Filling out the last step and saving it, ... >>> user.getControl('Name').value = 'Myself' >>> user.getControl('Street').value = '110 Main Street' >>> user.getControl('Zip').value = '01754' >>> user.getControl('City').value = 'Maynard' >>> user.getControl('Save').click() ... will allow the "Finish" button to show: >>> user.getControl('Finish') <SubmitControl name='form.buttons.finish' type='submit'> Clicking it, brings us to the final summary screen: >>> user.getControl('Finish').click() >>> user.url 'http://localhost:8080/summary.html'
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/wizard/README.txt
README.txt
__docformat__ = "reStructuredText" import datetime import zope.interface from zope.traversing.browser import absoluteURL from zope.viewlet.viewlet import CSSViewlet from zc.table import column from zc.table.interfaces import ISortableColumn from z3c.pagelet import browser from z3c.form import button, field, form, widget from z3c.form.interfaces import IAddForm from z3c.formui import layout from z3c.formdemo.browser import formatter from z3c.formdemo.sqlmessage import interfaces, sql SESSION_KEY = 'z3c.formdemo.sqlmessage' SQLMessageCSSViewlet = CSSViewlet('sqlmessage.css') DefaultDate = widget.ComputedWidgetAttribute( lambda adapter: datetime.date.today(), field=interfaces.IHelloWorld['when'], view=IAddForm) class ISQLMessagePage(zope.interface.Interface): """A marker interface for all SQL Hello World pages.""" class HelloWorldAddForm(layout.AddFormLayoutSupport, form.AddForm): zope.interface.implements(ISQLMessagePage) fields = field.Fields(interfaces.IHelloWorld) def create(self, data): return data def add(self, data): data['id'] = sql.getNextId() data['when'] = data['when'].toordinal() sql.addMessage(data) return data def nextURL(self): url = absoluteURL(self.context, self.request) return url + '/showAllSQLHelloWorld.html' class HelloWorldEditForm(layout.FormLayoutSupport, form.EditForm): zope.interface.implements(ISQLMessagePage) form.extends(form.EditForm) fields = field.Fields(interfaces.IHelloWorld) def getContent(self): msg = sql.getMessage(self.request.form['id']) content = dict( [(name, getattr(msg, name.upper())) for name in self.fields.keys()] ) content['when'] = datetime.date.fromordinal(content['when']) return content def applyChanges(self, data): changed = False for name, value in self.getContent().items(): if data[name] != value: changed = True data['when'] = data['when'].toordinal() if changed: id = self.request.form['id'] sql.updateMessage(id, data) return changed @button.buttonAndHandler(u'Apply and View', name='applyView') def handleApplyView(self, action): self.handleApply(self, action) if not self.widgets.errors: url = absoluteURL(self.context, self.request) url += '/showSQLHelloWorld.html?id=' + self.request['id'] self.request.response.redirect(url) class HelloWorldDisplayForm(layout.FormLayoutSupport, form.DisplayForm): zope.interface.implements(ISQLMessagePage) fields = field.Fields(interfaces.IHelloWorld) def getContent(self): msg = sql.getMessage(self.request.form['id']) content = dict( [(name, getattr(msg, name.upper())) for name in self.fields.keys()] ) content['when'] = datetime.date.fromordinal(content['when']) return content class SQLColumn(column.GetterColumn): zope.interface.implements(ISortableColumn) def getter(self, item, formatter): return getattr(item, self.name.upper()) def cell_formatter(self, value, item, formatter): return '<a href="showSQLHelloWorld.html?id=%s">%s</a>' %( item.ID, unicode(value)) class DateSQLColumn(SQLColumn): def getter(self, item, formatter): value = super(DateSQLColumn, self).getter(item, formatter) return datetime.date.fromordinal(value) class DeleteSQLColumn(column.Column): def renderCell(self, item, formatter): link = '<a href="showAllSQLHelloWorld.html?delete=%i">[Delete]</a>' return link % item.ID class HelloWorldOverview(browser.BrowserPagelet): zope.interface.implements(ISQLMessagePage) status = None columns = ( SQLColumn(u'Id', name='id'), SQLColumn(u'Who', name='who'), DateSQLColumn(u'When', name='when'), SQLColumn(u'What', name='what'), DeleteSQLColumn(u'', name='delete') ) def update(self): if 'initialize' in self.request.form: try: sql.initialize() except zope.rdb.DatabaseException, exc: self.status = "Database Message: " + exc.message elif 'delete' in self.request.form: try: sql.deleteMessage(self.request.form['delete']) except zope.rdb.DatabaseException, exc: self.status = "Database Message: " + exc.message try: messages = sql.queryAllMessages() except zope.rdb.DatabaseException, exc: # No message table exists yet. messages = () self.table = formatter.ListFormatter( self.context, self.request, messages, prefix = SESSION_KEY + '.', columns=self.columns, sort_on=[('id', False)]) self.table.sortKey = 'z3c.formdemo.sqlmessage.sort-on' self.table.cssClasses['table'] = 'message-list' self.table.widths = (50, 200, 100, 150, 100)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/sqlmessage/browser.py
browser.py
============================ SQL Hello World Message Demo ============================ The purpose of the SQL Hello World Message demo is to demonstrate how non-bject data can be manipulated and displayed using the form framework. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "SQL Hello World" link: >>> user.getLink('SQL Hello World').click() The initial page of the demo is the list of all messages. This screen exists, because the ZMI management screens are not helpful for unmapped relational data. >>> testing.printElement(user, "//h1") <h1>SQL Hello World Message Demo</h1> Let's make sure the database is truly empty: >>> testing.printElement(user, "//table/tbody", multiple=True) We can now initialize the database using one of the action links below the table: >>> user.getLink('[Initialize the database]').click() >>> testing.printElement(user, "//div[@class='summary']", multiple=True) The page returns with no notable messages. Clicking the link again results in an error, because the database is already initialized: >>> user.getLink('[Initialize the database]').click() >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Database Message: cannot create MSG, exists</div> Let's now add a new message: >>> user.getLink('[Add message]').click() You are now represented with the message add form. >>> user.url 'http://localhost:8080/addSQLHelloWorld.html' If we submit the form by clicking on add, ... >>> user.getControl('Add').click() ... the same page returns telling us we have some errors: >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">There were some errors.</div> This is because we forgot to enter the "Who" field, which is required: >>> testing.printElement(user, "//ul[@class='errors']/li") <li> Who: <div class="error">Required input is missing.</div> </li> Let's now fill out all the required fields and try to add the message again: >>> user.getControl('Who').value = u'Stephan' >>> user.getControl('When').value = u'7/1/07' >>> user.getControl('Add').click() Once submitted, the message is now added to the database and we are returned back to the overview: >>> testing.printElement(user, "//table/tbody/tr[1]") <tr class="odd"><td class="sorted-on"> <a href="showSQLHelloWorld.html?id=0">0</a> </td> <td class=""> <a href="showSQLHelloWorld.html?id=0">Stephan</a> </td> <td class=""> <a href="showSQLHelloWorld.html?id=0">2007-07-01</a> </td> <td class=""> <a href="showSQLHelloWorld.html?id=0">cool</a> </td> <td class=""> <a href="showAllSQLHelloWorld.html?delete=0">[Delete]</a> </td> </tr> Clicking on any data item, brings us to the message display screen: >>> user.getLink('Stephan').click() >>> testing.printElement(user, "//h1") <h1> A <span id="form-widgets-what" class="select-widget required choice-field"><span class="selected-option">cool</span></span> Hello World from <span id="form-widgets-who" class="text-widget required textline-field">Stephan</span> on <span id="form-widgets-when" class="text-widget required date-field">7/1/07</span> ! </h1> The message's edit form can be accessed by clicking on the "Edit Message" link: >>> user.getLink('Edit Message').click() When immediately pressing "Apply", a message appears telling us that no data has been changed: >>> user.getControl('Apply', index=0).click() >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">No changes were applied.</div> Let's now change the name and submit the form: >>> user.getControl('Who').value = u'Roger' >>> user.getControl('Apply', index=0).click() The page now informs us that the data has been updated: >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Data successfully updated.</div> When pressing the "Apply and View" button, the changed data is stored and the user is also forwarded to the view page again: >>> user.getControl('What').getControl('best').click() >>> user.getControl('Apply and View').click() Of course, the view shows the latest data: >>> testing.printElement(user, "//h1") <h1> A <span id="form-widgets-what" class="select-widget required choice-field"><span class="selected-option">best</span></span> Hello World from <span id="form-widgets-who" class="text-widget required textline-field">Roger</span> on <span id="form-widgets-when" class="text-widget required date-field">7/1/07</span> ! </h1> From the display screen you can also return to the overview: >>> user.getLink('[Show All Messages]').click() >>> user.url 'http://localhost:8080/showAllSQLHelloWorld.html' Let's now add a new message: >>> user.getLink('[Add message]').click() >>> user.getControl('Who').value = u'Stephan' >>> user.getControl('When').value = u'7/2/07' >>> user.getControl('Add').click() As you probably already guessed, the table headers can be used to sort items. Clicking on the "Id" table header cell, will leave the order, since the ordering must be initialized. The second time the order is reversed: >>> user.getLink('Id').click() >>> user.getLink('Id').click() >>> testing.printElement(user, "//table/tbody/tr/td[1]/a/text()", ... multiple=True, serialize=False) 1 0 Selecting another header will sort on it. Let's choose the "Who" column; clicking on it once sorts it in ascending order: >>> user.getLink('Who').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/a/text()", ... multiple=True, serialize=False) Roger Stephan Clicking it again, reverses the order: >>> user.getLink('Who').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/a/text()", ... multiple=True, serialize=False) Stephan Roger To delete a contact, you Simply click on the "Delete" link of the corresponding row: >>> user.getLink('[Delete]', index=1).click() The message is now gone from the table: >>> user.getLink('Roger') Traceback (most recent call last): ... LinkNotFoundError
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/sqlmessage/README.txt
README.txt
__docformat__ = "reStructuredText" import zope.interface from zope.traversing.browser import absoluteURL from zope.viewlet.viewlet import CSSViewlet from z3c.pagelet import browser from z3c.form import button, field, form, group, widget from zc.table import column from z3c.formdemo.browser import formatter from z3c.formdemo.questionnaire import interfaces, questionnaire from z3c.formui import layout QuestionnaireCSSViewlet = CSSViewlet('questionnaire.css') class IQuestionnaireGroup(zope.interface.Interface): """Questionnaire Group""" class IQuestionnairePage(zope.interface.Interface): """Questionnaire Page""" class DevelopmentExperienceGroup(group.Group): zope.interface.implements(IQuestionnaireGroup) label = u'Development Experience' fields = field.Fields(interfaces.IQuestionnaire).select( 'zope2', 'plone', 'zope3', 'five') class ContributorExperienceGroup(group.Group): zope.interface.implements(IQuestionnaireGroup) label = u'Contributor Experience' fields = field.Fields(interfaces.IQuestionnaire).select( 'contributor', 'years', 'zopeId') class QuestionnaireAddForm(layout.AddFormLayoutSupport, group.GroupForm, form.AddForm): zope.interface.implements(IQuestionnairePage) label = u'Zope Developer Questionnaire' fields = field.Fields(interfaces.IQuestionnaire).select('name', 'age') groups = (DevelopmentExperienceGroup, ContributorExperienceGroup) def create(self, data): return questionnaire.Questionnaire(**data) def add(self, object): count = 0 while 'questionnaire-%i' %count in self.context: count += 1; self._name = 'questionnaire-%i' %count self.context[self._name] = object return object def nextURL(self): url = absoluteURL(self.context, self.request) return url + '/questionnaireResults.html' SubmitLabel = button.StaticButtonActionAttribute( u'Submit Questionnaire', button=form.AddForm.buttons['add'], form=QuestionnaireAddForm) def getDescriptionAsLabel(value): return value.field.description QuestionLabel = widget.ComputedWidgetAttribute( getDescriptionAsLabel, view=IQuestionnaireGroup) class DataColumn(column.SortingColumn): def __init__(self, field): super(DataColumn, self).__init__(field.title, field.__name__) def renderCell(self, item, formatter): return item.widgets[self.name].render() def getSortKey(self, item, formatter): return item.widgets[self.name].value class QuestionnaireRow(form.DisplayForm): fields = field.Fields(interfaces.IQuestionnaire) class QuestionnaireResults(browser.BrowserPagelet): zope.interface.implements(IQuestionnairePage) rowFields = field.Fields(interfaces.IQuestionnaire) def getContent(self): return [obj for obj in self.context.values() if interfaces.IQuestionnaire.providedBy(obj)] def update(self): super(QuestionnaireResults, self).update() rows = [] for questionnaire in self.getContent(): row = QuestionnaireRow(questionnaire, self.request) row.update() rows.append(row) columns = [DataColumn(field.field) for field in self.rowFields.values()] self.table = formatter.ListFormatter( self.context, self.request, rows, prefix = 'formdemo.questionnaire.', columns=columns, sort_on=[('name', False)]) self.table.widths = (160, 45, 65, 55, 65, 50, 70, 55, 100) for col in ('age', 'zope2', 'plone', 'zope3', 'five', 'contributor', 'years', 'zopeId'): self.table.columnCSS[col] = 'right' self.table.sortKey = 'formdemo.questionnaire.sort-on'
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/questionnaire/browser.py
browser.py
================== Questionnaire Demo ================== The purpose of the questionnaire demo is demonstrate the concept of field groups and attribute value adapters for fields. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "All widgets" link: >>> user.getLink('Questionnaire').click() The first screen you see is the questionnaire results screen. >>> testing.printElement(user, "//h1") <h1>Zope Developer Questionnaire Results</h1> Initially there are no questionnaires, so the screen contains little information. Let's first fill out a questionnaire by click on the link below the table. >>> user.getLink('Fill out Questionnaire').click() The user is now presented with the questionnaire screen, which is organized into three groups. Let's fill out the questionnaire: >>> user.getControl('Name').value = u'Stephan Richter' >>> user.getControl('Age').value = u'27' >>> user.getControl(name='form.widgets.zope2:list')\ ... .getControl(value='true').click() >>> user.getControl(name='form.widgets.plone:list')\ ... .getControl(value='false').click() >>> user.getControl(name='form.widgets.zope3:list')\ ... .getControl(value='true').click() >>> user.getControl(name='form.widgets.five:list')\ ... .getControl(value='false').click() >>> user.getControl(name='form.widgets.contributor:list')\ ... .getControl(value='true').click() >>> user.getControl('have you contributed').value = u'5' >>> user.getControl('What is your Zope Id?').value = u'srichter' >>> user.getControl('Submit Questionnaire').click() Once the questionnaire has been submitted, the user is returned to the results screen. Now the table has an entry: >>> testing.printElement(user, "//table/tbody/tr[1]") <tr class="odd"><td class="sorted-on"> <span id="form-widgets-name" class="text-widget required textline-field">Stephan Richter</span> </td> <td class="right"> <span id="form-widgets-age" class="text-widget required int-field">27</span> </td> <td class="right"> <span id="form-widgets-zope2" class="radio-widget required bool-field"><span class="selected-option">yes</span></span> </td> <td class="right"> <span id="form-widgets-plone" class="radio-widget required bool-field"><span class="selected-option">no</span></span> </td> <td class="right"> <span id="form-widgets-zope3" class="radio-widget required bool-field"><span class="selected-option">yes</span></span> </td> <td class="right"> <span id="form-widgets-five" class="radio-widget required bool-field"><span class="selected-option">no</span></span> </td> <td class="right"> <span id="form-widgets-contributor" class="radio-widget required bool-field"><span class="selected-option">yes</span></span> </td> <td class="right"> <span id="form-widgets-years" class="text-widget int-field">5</span> </td> <td class="right"> <span id="form-widgets-zopeId" class="text-widget textline-field">srichter</span> </td> </tr> Let's now fill out another questionnaire: >>> user.getLink('Fill out Questionnaire').click() >>> user.getControl('Name').value = u'Roger Ineichen' >>> user.getControl('Age').value = u'39' >>> user.getControl(name='form.widgets.zope2:list')\ ... .getControl(value='true').click() >>> user.getControl(name='form.widgets.plone:list')\ ... .getControl(value='true').click() >>> user.getControl(name='form.widgets.zope3:list')\ ... .getControl(value='true').click() >>> user.getControl(name='form.widgets.five:list')\ ... .getControl(value='false').click() >>> user.getControl(name='form.widgets.contributor:list')\ ... .getControl(value='true').click() >>> user.getControl('have you contributed').value = u'4' >>> user.getControl('What is your Zope Id?').value = u'projekt01' >>> user.getControl('Submit Questionnaire').click() Now that we have two entries, we can use the table headers cells to sort them. By default they are sorted by name: >>> testing.printElement(user, "//table/tbody/tr/td[1]/span/text()", ... multiple=True, serialize=False) Roger Ineichen Stephan Richter Clicking on the "Name" table header cell, will leave the order, since the ordering must be initialized. The second time the order is reversed: >>> user.getLink('Name').click() >>> user.getLink('Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[1]/span/text()", ... multiple=True, serialize=False) Stephan Richter Roger Ineichen Selecting another header will sort on it. Let's choose the age; clicking on it once sorts it in ascending order: >>> user.getLink('Age').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/span/text()", ... multiple=True, serialize=False) 27 39 Clicking it again, reverses the order: >>> user.getLink('Age').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/span/text()", ... multiple=True, serialize=False) 39 27 Finally, let's make sure that all headers are linked: >>> user.getLink('Zope 2') <Link text='Zope 2' url='...?sort-on=formdemo.questionnaire.zope2'> >>> user.getLink('Plone') <Link text='Plone' url='...?sort-on=formdemo.questionnaire.plone'> >>> user.getLink('Zope 3') <Link text='Zope 3' url='...?sort-on=formdemo.questionnaire.zope3'> >>> user.getLink('Five') <Link text='Five' url='...?sort-on=formdemo.questionnaire.five'> >>> user.getLink('Contrib.') <Link text='Contrib.' url='...?sort-on=formdemo.questionnaire.contributor'> >>> user.getLink('Years') <Link text='Years' url='...?sort-on=formdemo.questionnaire.years'> >>> user.getLink('Zope Id') <Link text='Zope Id' url='...?sort-on=formdemo.questionnaire.zopeId'>
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/questionnaire/README.txt
README.txt
__docformat__ = "reStructuredText" import datetime import zope.component import zope.interface import zope.schema from zope.schema import vocabulary from z3c.form import interfaces, widget from z3c.form.browser import select class DateSelectWidget(widget.Widget): selects = ( ('year', range(1920, 2011), 0), ('month', range(1, 13), 1), ('day', range(1, 32), 2) ) def update(self): for (name, options, loc) in self.selects: selectWidget = select.SelectWidget(self.request) selectWidget.terms = vocabulary.SimpleVocabulary.fromValues(options) selectWidget.required = True selectWidget.name = self.name + '.' + name selectWidget.id = selectWidget.name.replace('.', '-') selectWidget.klass = name setattr(self, name, selectWidget) super(DateSelectWidget, self).update() for (name, options, loc) in self.selects: selectWidget = getattr(self, name) if self.value and not selectWidget.value: selectWidget.value = (self.value[loc],) selectWidget.update() def extract(self, default=interfaces.NOVALUE): """See z3c.form.interfaces.IWidget.""" value = (self.year.extract(default), self.month.extract(default), self.day.extract(default)) if default in value: return default return value @zope.component.adapter(zope.schema.interfaces.IDate, interfaces.IFormLayer) @zope.interface.implementer(interfaces.IFieldWidget) def DateSelectFieldWidget(field, request): """IFieldWidget factory for DateSelectWidget.""" return widget.FieldWidget(field, DateSelectWidget(request)) class DateSelectDataConverter(object): zope.component.adapts(zope.schema.interfaces.IDate, DateSelectWidget) zope.interface.implements(interfaces.IDataConverter) def __init__(self, field, widget): self.field = field self.widget = widget def toWidgetValue(self, value): """See interfaces.IDataConverter""" if value is self.field.missing_value: return None return (str(value.year), str(value.month), str(value.day)) def toFieldValue(self, value): """See interfaces.IDataConverter""" if value == None: return self.field.missing_value return datetime.date(*[int(part[0]) for part in value])
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/dateselect.py
dateselect.py
if(window.addEventListener)window.addEventListener('load',textShadows,false); else if(window.attachEvent)window.attachEvent('onload',textShadows); function setStyles(o,s){ var i; s=s.split(';'); for(i in s){ var p=s[i].split(':'); o.style[p[0]]=p[1]; } } function textShadows(){ var ua=navigator.userAgent; if(ua.indexOf('KHTML')>=0&&!(ua.indexOf('Safari')>=0))return; var ss=document.styleSheets,a; for(a in ss){ var theRules=[],b; if(ss[a].cssRules)theRules=ss[a].cssRules; else if(ss[a].rules)theRules=ss[a].rules; for(b=0; b < theRules.length; b++){ var selector=theRules[b].selectorText,r=theRules[b].style.cssText; if(/text-shadow/.test(r)){ r=r.replace(/([ ,]) /g,'$1').replace(/.*text-shadow[ :]+/,'').replace(/[ ]*;.*/,''); var shadows=r.split(','),k,els=cssQuery(selector),l; for(l in els){ var x=parseInt(els[l].offsetLeft),y=parseInt(els[l].offsetTop),el3=els[l].cloneNode(true); setStyles(el3,'position:absolute;zIndex:50;margin:0'); for(k in shadows){ var parts=shadows[k].split(' '); var newX=x+parseInt(parts[1]),newY=y+parseInt(parts[2]),rad=parseInt(parts[3]); for(m=0-rad;m<=rad;++m)for(n=0-rad;n<=rad;++n)showShadow(els[l],newX+m,newY+n,parts[0]); var el2=el3.cloneNode(true); setStyles(el2,'left:'+x+'px;top:'+y+'px'); els[l].parentNode.appendChild(el2); } } } } } } function showShadow(el,x,y,color){ var el2=el.cloneNode(true); setStyles(el2,'position:absolute;color:'+color+';left:'+x+'px;top:'+y+'px;margin:0;textShadow:none;zIndex:49'); el2.style.opacity='.08'; el2.style.filter='alpha(opacity=8)'; el.parentNode.appendChild(el2); } /* This work is licensed under a Creative Commons License. License: http://creativecommons.org/licenses/by/1.0/ You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must give the original author credit Author: Dean Edwards/2004 Web: http://dean.edwards.name/ */ /* keeping code tidy! */ /* extendible css query function for common platforms tested on IE5.0/5.5/6.0, Mozilla 1.6/Firefox 0.8, Opera 7.23/7.5 (all windows platforms - somebody buy me a mac!) */ // ----------------------------------------------------------------------- // css query engine // ----------------------------------------------------------------------- var cssQuery=function() { var version="1.0.1"; // timestamp: 2004/05/25 // constants var STANDARD_SELECT=/^[^>\+~\s]/; var STREAM=/[\s>\+~:@#\.]|[^\s>\+~:@#\.]+/g; var NAMESPACE=/\|/; var IMPLIED_SELECTOR=/([\s>\+~\,]|^)([\.:#@])/g; var ASTERISK ="$1*$2"; var WHITESPACE=/^\s+|\s*([\+\,>\s;:])\s*|\s+$/g; var TRIM="$1"; var NODE_ELEMENT=1; var NODE_TEXT=3; var NODE_DOCUMENT=9; // sniff for explorer (cos of one little bug) var isMSIE=/MSIE/.test(navigator.appVersion), isXML; // cache results for faster processing var cssCache={}; // this is the query function function cssQuery(selector, from) { if (!selector) return []; var useCache=arguments.callee.caching && !from; from=(from) ? (from.constructor == Array) ? from : [from] : [document]; isXML=checkXML(from[0]); // process comma separated selectors var selectors=parseSelector(selector).split(","); var match=[]; for (var i in selectors) { // convert the selector to a stream selector=toStream(selectors[i]); // process the stream var j=0, token, filter, cacheSelector="", filtered=from; while (j < selector.length) { token=selector[j++]; filter=selector[j++]; cacheSelector += token + filter; // process a token/filter pair filtered=(useCache && cssCache[cacheSelector]) ? cssCache[cacheSelector] : select(filtered, token, filter); if (useCache) cssCache[cacheSelector]=filtered; } match=match.concat(filtered); } // return the filtered selection return match; }; cssQuery.caching=false; cssQuery.reset=function() { cssCache={}; }; cssQuery.toString=function () { return "function cssQuery() {\n [version " + version + "]\n}"; }; var checkXML=(isMSIE) ? function(node) { if (node.nodeType != NODE_DOCUMENT) node=node.document; return node.mimeType == "XML Document"; } : function(node) { if (node.nodeType == NODE_DOCUMENT) node=node.documentElement; return node.localName != "HTML"; }; function parseSelector(selector) { return selector // trim whitespace .replace(WHITESPACE, TRIM) // encode attribute selectors .replace(attributeSelector.ALL, attributeSelector.ID) // e.g. ".class1" --> "*.class1" .replace(IMPLIED_SELECTOR, ASTERISK); }; // convert css selectors to a stream of tokens and filters // it's not a real stream. it's just an array of strings. function toStream(selector) { if (STANDARD_SELECT.test(selector)) selector=" " + selector; return selector.match(STREAM) || []; }; var pseudoClasses={ // static // CSS1 "link": function(element) { for (var i=0; i < document.links; i++) { if (document.links[i] == element) return true; } }, "visited": function(element) { // can't do this without jiggery-pokery }, // CSS2 "first-child": function(element) { return !previousElement(element); }, // CSS3 "last-child": function(element) { return !nextElement(element); }, "root": function(element) { var document=element.ownerDocument || element.document; return Boolean(element == document.documentElement); }, "empty": function(element) { for (var i=0; i < element.childNodes.length; i++) { if (isElement(element.childNodes[i]) || element.childNodes[i].nodeType == NODE_TEXT) return false; } return true; } // add your own... }; var QUOTED=/([\'\"])[^\1]*\1/; function quote(value) {return (QUOTED.test(value)) ? value : "'" + value + "'"}; function unquote(value) {return (QUOTED.test(value)) ? value.slice(1, -1) : value}; var attributeSelectors=[]; function attributeSelector(attribute, compare, value) { // properties this.id=attributeSelectors.length; // build the test expression var test="element."; switch (attribute.toLowerCase()) { case "id": test += "id"; break; case "class": test += "className"; break; default: test += "getAttribute('" + attribute + "')"; } // continue building the test expression switch (compare) { case "=": test += "==" + quote(value); break; case "~=": test="/(^|\\s)" + unquote(value) + "(\\s|$)/.test(" + test + ")"; break; case "|=": test="/(^|-)" + unquote(value) + "(-|$)/.test(" + test + ")"; break; } push(attributeSelectors, new Function("element", "return " + test)); }; attributeSelector.prototype.toString=function() { return attributeSelector.PREFIX + this.id; }; // constants attributeSelector.PREFIX="@"; attributeSelector.ALL=/\[([^~|=\]]+)([~|]?=?)([^\]]+)?\]/g; // class methods attributeSelector.ID=function(match, attribute, compare, value) { return new attributeSelector(attribute, compare, value); }; // select a set of matching elements. // "from" is an array of elements. // "token" is a character representing the type of filter // e.g. ">" means child selector // "filter" represents the tag name, id or class name that is being selected // the function returns an array of matching elements function select(from, token, filter) { //alert("token="+token+",filter="+filter); var namespace=""; if (NAMESPACE.test(filter)) { filter=filter.split("|"); namespace=filter[0]; filter=filter[1]; } var filtered=[], i; switch (token) { case " ": // descendant for (i in from) { var subset=getElementsByTagNameNS(from[i], filter, namespace); for (var j=0; j < subset.length; j++) { if (isElement(subset[j]) && (!namespace || compareNamespace(subset[j], namespace))) push(filtered, subset[j]); } } break; case ">": // child for (i in from) { var subset=from[i].childNodes; for (var j=0; j < subset.length; j++) if (compareTagName(subset[j], filter, namespace)) push(filtered, subset[j]); } break; case "+": // adjacent (direct) for (i in from) { var adjacent=nextElement(from[i]); if (adjacent && compareTagName(adjacent, filter, namespace)) push(filtered, adjacent); } break; case "~": // adjacent (indirect) for (i in from) { var adjacent=from[i]; while (adjacent=nextElement(adjacent)) { if (adjacent && compareTagName(adjacent, filter, namespace)) push(filtered, adjacent); } } break; case ".": // class filter=new RegExp("(^|\\s)" + filter + "(\\s|$)"); for (i in from) if (filter.test(from[i].className)) push(filtered, from[i]); break; case "#": // id for (i in from) if (from[i].id == filter) push(filtered, from[i]); break; case "@": // attribute selector filter=attributeSelectors[filter]; for (i in from) if (filter(from[i])) push(filtered, from[i]); break; case ":": // pseudo-class (static) filter=pseudoClasses[filter]; for (i in from) if (filter(from[i])) push(filtered, from[i]); break; } return filtered; }; var getElementsByTagNameNS=(isMSIE) ? function(from, tagName) { return (tagName == "*" && from.all) ? from.all : from.getElementsByTagName(tagName); } : function(from, tagName, namespace) { return (namespace) ? from.getElementsByTagNameNS("*", tagName) : from.getElementsByTagName(tagName); }; function compareTagName(element, tagName, namespace) { if (namespace && !compareNamespace(element, namespace)) return false; return (tagName == "*") ? isElement(element) : (isXML) ? (element.tagName == tagName) : (element.tagName == tagName.toUpperCase()); }; var PREFIX=(isMSIE) ? "scopeName" : "prefix"; function compareNamespace(element, namespace) { return element[PREFIX] == namespace; }; // return the previous element to the supplied element // previousSibling is not good enough as it might return a text or comment node function previousElement(element) { while ((element=element.previousSibling) && !isElement(element)) continue; return element; }; // return the next element to the supplied element function nextElement(element) { while ((element=element.nextSibling) && !isElement(element)) continue; return element; }; function isElement(node) { return Boolean(node.nodeType == NODE_ELEMENT && node.tagName != "!"); }; // use a baby push function because IE5.0 doesn't support Array.push function push(array, item) { array[array.length]=item; }; // fix IE5.0 String.replace if ("i".replace(/i/,function(){return""})) { // preserve String.replace var string_replace=String.prototype.replace; // create String.replace for handling functions var function_replace=function(regexp, replacement) { var match, newString="", string=this; while ((match=regexp.exec(string))) { // five string replacement arguments is sufficent for cssQuery newString += string.slice(0, match.index) + replacement(match[0], match[1], match[2], match[3], match[4]); string=string.slice(match.lastIndex); } return newString + string; }; // replace String.replace String.prototype.replace=function (regexp, replacement) { this.replace=(typeof replacement == "function") ? function_replace : string_replace; return this.replace(regexp, replacement); }; } return cssQuery; }();
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/text-shadow.js
text-shadow.js
__docformat__ = "reStructuredText" import zope.interface import zope.schema from zope.schema import vocabulary AddressNamesVocabulary = vocabulary.SimpleVocabulary(( vocabulary.SimpleTerm('home', title=u'Home'), vocabulary.SimpleTerm('work', title=u'Work'), vocabulary.SimpleTerm('other', title=u'Other') )) class IAddress(zope.interface.Interface): """An address.""" street = zope.schema.TextLine( title=u'Street', description=u'Street name and number.') city = zope.schema.TextLine( title=u'City', description=u'City.') state = zope.schema.TextLine( title=u'State', description=u'State or Province.') zip = zope.schema.TextLine( title=u'ZIP', description=u'ZIP Code.') class IEMail(zope.interface.Interface): """An E-mail address.""" user = zope.schema.TextLine( title=u'User') host = zope.schema.TextLine( title=u'Host') fullAddress = zope.schema.TextLine( title=u'E-mail Address', description=u'The full E-mail address.') class IPhone(zope.interface.Interface): """A phone number.""" countryCode = zope.schema.TextLine( title=u'Country Code', default=u'1') areaCode = zope.schema.TextLine( title=u'Area Code') number = zope.schema.TextLine( title=u'Number') extension = zope.schema.TextLine( title=u'Extension', required=False) class IContact(zope.interface.Interface): """A contact in the address book.""" firstName = zope.schema.TextLine( title=u'First Name', description=u'First name of the person.') lastName = zope.schema.TextLine( title=u'Last Name', description=u'Last name of the person.') birthday = zope.schema.Date( title=u'Birthday', description=u'Birthday of the person.', required=False) addresses = zope.schema.Dict( title=u'Addresses', description=u'A mapping of addresses', key_type=zope.schema.Choice( __name__='addressName', vocabulary=AddressNamesVocabulary), value_type=zope.schema.Object(schema=IAddress)) emails = zope.schema.List( title=u'E-mails', description=u'E-mails of the person.', value_type=zope.schema.Object(schema=IEMail)) homePhone = zope.schema.Object( title=u'Home Phone', description=u'Home Phone Number.', schema=IPhone) cellPhone = zope.schema.Object( title=u'Cell Phone', description=u'Cell Phone Number.', schema=IPhone, required=False) workPhone = zope.schema.Object( title=u'Work Phone', description=u'Work Phone Number.', schema=IPhone, required=False)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/interfaces.py
interfaces.py
__docformat__ = "reStructuredText" import zope.component import zope.location from zope.session.interfaces import ISession from zope.pagetemplate.interfaces import IPageTemplate from zope.publisher import browser from zope.security.proxy import removeSecurityProxy from zope.traversing.browser import absoluteURL from zope.viewlet.viewlet import CSSViewlet, JavaScriptViewlet from z3c.template.interfaces import ILayoutTemplate from zc.table import column from zc.table.interfaces import ISortableColumn from z3c.form import form, field, button, subform from z3c.formdemo.browser import formatter from z3c.formdemo.addressbook import interfaces, contact, dateselect SESSION_KEY = 'z3c.formdemo.addressbook' AddressBookCSSViewlet = CSSViewlet('addressbook.css') TextShadowViewlet = JavaScriptViewlet('text-shadow.js') class AddressForm(subform.EditSubForm, form.EditForm): form.extends(subform.EditSubForm) fields = field.Fields(interfaces.IAddress) name = None deleted = False # In this application, we do not want this message noChangesMessage = None def updateWidgets(self): super(AddressForm, self).updateWidgets() for name, widget in self.widgets.items(): widget.addClass(name) @property def title(self): return interfaces.AddressNamesVocabulary.getTerm(self.name).title @button.handler(form.AddForm.buttons['add']) def handleAdd(self, action): self.handleApply(self, action) @button.buttonAndHandler(u'Delete') def handleDelete(self, action): addresses = self.getContent().__parent__ del addresses[self.name] self.deleted = True class AddressesForm(form.AddForm): """Form to manage addresses.""" # Select the field that specifies the address name. fields = field.Fields(interfaces.IContact['addresses'].key_type) parentForm = None def create(self, data): address = contact.Address() address.__name__ = data['addressName'] return address def add(self, object): addressbook = self.getContent() # Make sure that an address cannot be added twice. if object.__name__ in addressbook: self.status = u'Address already provided for contact.' return None addressbook[object.__name__] = object return object def getContent(self): # Get the address container from the contact if interfaces.IContact.providedBy(self.context): return self.context.addresses # We are in the process of adding a contact, so store the addresses # container in a session variable. session = ISession(self.request)[SESSION_KEY] if 'addresses' not in session: session['addresses'] = contact.Addresses() return session['addresses'] def update(self): # Make sure that we have a unique prefix. self.prefix = self.parentForm.prefix + 'addresses.' super(AddressesForm, self).update() # For each address, create an address form. self.addressForms = [] for name, address in self.getContent().items(): form = AddressForm(address, self.request, self.parentForm) form.name = str(name) # The prefix is created at runtime to guarantee uniqueness form.prefix = self.prefix + str(name) + '.' form.update() # Updating the address can also mean its deletion. If deleted, it # is not added to the list. if not form.deleted: self.addressForms.append(form) def render(self): # Boilerplate when workign with view templates. template = zope.component.getMultiAdapter( (self, self.request), IPageTemplate) return template(self) class PhoneForm(subform.EditSubForm): form.extends(subform.EditSubForm) fields = field.Fields(interfaces.IPhone) attrName = None error = None mode = 'input' def updateWidgets(self): super(PhoneForm, self).updateWidgets() for name, widget in self.widgets.items(): widget.addClass(name) def getContent(self): # Get the phone attribute from the contact if interfaces.IContact.providedBy(self.context): return getattr(self.context, self.attrName) # We are in the process of adding a contact, so store the phone # in a session variable. session = ISession(self.request)[SESSION_KEY] if self.attrName not in session: session[self.attrName] = contact.Phone() return session[self.attrName] @button.handler(form.AddForm.buttons['add']) def handleAdd(self, action): self.handleApply(self, action) @property def id(self): return (self.prefix + 'widgets.countryCode').replace('.', '-') @property def label(self): return interfaces.IContact[self.attrName].title @property def required(self): return interfaces.IContact[self.attrName].required class PhonesForm(browser.BrowserPage): parentForm = None def update(self): self.prefix = self.parentForm.prefix + 'phones.' self.forms = [] for name in ('homePhone', 'workPhone', 'cellPhone'): form = PhoneForm(self.context, self.request, self.parentForm) form.prefix = self.prefix + name + '.' form.attrName = name form.update() self.forms.append(form) def render(self): template = zope.component.getMultiAdapter( (self, self.request), IPageTemplate) return template(self) class EMailForm(subform.EditSubForm, form.EditForm): form.extends(subform.EditSubForm) fields = field.Fields(interfaces.IEMail['fullAddress']) index = None deleted = False # In this application, we do not want this message noChangesMessage = None def updateWidgets(self): super(EMailForm, self).updateWidgets() for name, widget in self.widgets.items(): widget.addClass(u'email') @button.handler(form.AddForm.buttons['add']) def handleAdd(self, action): self.handleApply(self, action) @button.buttonAndHandler(u'Delete') def handleDelete(self, action): emails = self.getContent().__parent__ del emails[self.index] self.deleted = True class EMailsForm(form.AddForm): fields = field.Fields(interfaces.IEMail['fullAddress']) parentForm = None def updateWidgets(self): super(EMailsForm, self).updateWidgets() for name, widget in self.widgets.items(): widget.addClass(u'email') def create(self, data): address = contact.EMail(**data) return address def add(self, object): self.getContent().append(object) zope.location.locate(object, self.getContent()) self.widgets.ignoreRequest = True self.widgets.update() return object def getContent(self): # Get the address container from the contact if interfaces.IContact.providedBy(self.context): return self.context.emails # We are in the process of adding a contact, so store the email list # in a session variable. session = ISession(self.request)[SESSION_KEY] if 'emails' not in session: session['emails'] = contact.EMails() return session['emails'] def update(self): self.prefix = self.parentForm.prefix + 'emails.' super(EMailsForm, self).update() self.emailForms = [] for index, email in enumerate(self.getContent()): form = EMailForm(email, self.request, self.parentForm) form.index = index form.prefix = self.prefix + str(index) + '.' form.update() if not form.deleted: self.emailForms.append(form) def render(self): template = zope.component.getMultiAdapter( (self, self.request), IPageTemplate) return template(self) class ContactAddForm(form.AddForm): fields = field.Fields(interfaces.IContact).select( 'firstName', 'lastName', 'birthday') fields['birthday'].widgetFactory = dateselect.DateSelectFieldWidget prefix = 'contact.add.' def update(self): self.updateWidgets() self.updateActions() self.addressesForm = AddressesForm(self.context, self.request) self.addressesForm.parentForm = self self.addressesForm.update() self.phonesForm = PhonesForm(self.context, self.request) self.phonesForm.parentForm = self self.phonesForm.update() self.emailsForm = EMailsForm(self.context, self.request) self.emailsForm.parentForm = self self.emailsForm.update() self.actions.execute() def create(self, data): newContact = contact.Contact(**data) newContact.addresses = self.addressesForm.getContent() zope.location.locate(newContact.addresses, newContact, 'addresses') del ISession(self.request)[SESSION_KEY]['addresses'] for phoneForm in self.phonesForm.forms: phone = phoneForm.getContent() zope.location.locate(phone, newContact, phoneForm.attrName) setattr(newContact, phoneForm.attrName, phone) del ISession(self.request)[SESSION_KEY][phoneForm.attrName] newContact.emails = self.emailsForm.getContent() zope.location.locate(newContact.emails, newContact, 'emails') del ISession(self.request)[SESSION_KEY]['emails'] return newContact def add(self, object): count = 0 while 'contact-%i' %count in self.context: count += 1; self._name = 'contact-%i' %count self.context[self._name] = object return object def nextURL(self): return self.request.getURL() AddContactLabel = button.StaticButtonActionAttribute( u'Add Contact', button=form.AddForm.buttons['add'], form=ContactAddForm) class ContactEditForm(form.EditForm): form.extends(form.EditForm) fields = field.Fields(interfaces.IContact).select( 'firstName', 'lastName', 'birthday') fields['birthday'].widgetFactory = dateselect.DateSelectFieldWidget prefix = 'contact.edit.' # In this application, we do not want this message noChangesMessage = None @button.buttonAndHandler(u'Delete') def handleDelete(self, action): # Delete the contact from the address book contact = self.getContent() addressbook = contact.__parent__ del addressbook[contact.__name__] # Reset the selected item ISession(self.request)[SESSION_KEY]['selectedContact'] = None @button.buttonAndHandler(u'Done') def handleDone(self, action): # Reset the selected item ISession(self.request)[SESSION_KEY]['selectedContact'] = None def update(self): super(ContactEditForm, self).update() self.addressesForm = AddressesForm(self.context, self.request) self.addressesForm.parentForm = self self.addressesForm.update() self.phonesForm = PhonesForm(self.context, self.request) self.phonesForm.parentForm = self self.phonesForm.update() self.emailsForm = EMailsForm(self.context, self.request) self.emailsForm.parentForm = self self.emailsForm.update() class SelectContactColumn(column.GetterColumn): zope.interface.implements(ISortableColumn) def renderCell(self, item, formatter): value = super(SelectContactColumn, self).renderCell(item, formatter) return '<a href="%s?selectContact=%s">%s</a>' %( formatter.request.getURL(), item.__name__, value) class AddressBook(browser.BrowserPage): columns = ( SelectContactColumn( u'Last Name', lambda i, f: i.lastName, name='lastName'), SelectContactColumn( u'First Name', lambda i, f: i.firstName, name='firstName'), ) @apply def selectedContact(): def get(self): session = ISession(self.request)[SESSION_KEY] return session.get('selectedContact') def set(self, value): session = ISession(self.request)[SESSION_KEY] # The session data is stored in the ZODB, so we must remove # security proxies. session['selectedContact'] = removeSecurityProxy(value) return property(get, set) def update(self): # Select a new contact if 'selectContact' in self.request: self.selectedContact = self.context[self.request['selectContact']] # Setup the form if self.selectedContact: self.form = ContactEditForm(self.selectedContact, self.request) self.form.update() if not self.selectedContact: self.form = ContactAddForm(self.context, self.request) self.form.update() # Setup the table rows = [content for content in self.context.values() if interfaces.IContact.providedBy(content)] self.table = formatter.SelectedItemFormatter( self.context, self.request, rows, prefix = SESSION_KEY + '.', columns=self.columns, sort_on=[('lastName', False)]) self.table.sortKey = 'z3c.formdemo.addressbook.sort-on' self.table.cssClasses['table'] = 'contact-list' self.table.widths = (150, 150) self.table.selectedItem = self.selectedContact def __call__(self): self.update() layout = zope.component.getMultiAdapter((self, self.request), ILayoutTemplate) return layout(self)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/browser.py
browser.py
================ Addressbook Demo ================ The purpose of the addressbook demo is to demonstrate a complex, form-driven UI with several sub-forms and table-integration. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "Address Book" link: >>> user.getLink('Address Book').click() There is only one screen for this demo. In it you see the table of all contacts on the left side and on the right side is the contact form. Initially, this is an add form. >>> testing.printElement(user, "//h1") <h1><span>Address Book Demo</span></h1> So let's start by filling out the add form. The first portion contains basic personal information: >>> user.getControl('First Name').value = 'Stephan' >>> user.getControl('Last Name').value = 'Richter' >>> user.getControl(name='contact.add.widgets.birthday.day:list')\ ... .getControl('25').click() >>> user.getControl(name='contact.add.widgets.birthday.year:list')\ ... .getControl('1980').click() In the second portion we can add any number of addresses. Let's just add a home address: >>> user.getControl('Add', index=0).click() >>> user.getControl('Street').value = '110 Main Street' >>> user.getControl('City').value = 'Maynard' >>> user.getControl('State').value = 'MA' >>> user.getControl('ZIP').value = '01754' You cannot add the same address twice: >>> user.getControl('Add', index=0).click() >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Address already provided for contact.</div> When accidently adding another address, ... >>> user.getControl(name='contact.add.addresses.widgets.addressName:list')\ ... .getControl('Work').click() >>> user.getControl('Add', index=0).click() you can delete it any time: >>> user.getControl('Delete', index=1).click() Let's now add the home phone number, because it is a required field: >>> user.getControl(name='contact.add.phones.homePhone.widgets.countryCode')\ ... .value = '+1' >>> user.getControl(name='contact.add.phones.homePhone.widgets.areaCode')\ ... .value = '555' >>> user.getControl(name='contact.add.phones.homePhone.widgets.number')\ ... .value = '127-1284' Finally, the user is requested to enter the E-mail addresses of the contact; we have two in this case: >>> user.getControl(name='contact.add.emails.widgets.fullAddress')\ ... .value = '[email protected]' >>> user.getControl('Add', index=1).click() >>> user.getControl(name='contact.add.emails.widgets.fullAddress')\ ... .value = '[email protected]' >>> user.getControl('Add', index=1).click() Once all the information has been provided, we can add the contact: >>> user.getControl('Add Contact').click() The new contact appears now in the contact list: >>> testing.printElement(user, "//table/tbody/tr[1]") <tr class="odd"><td class="sorted-on"> <a href="...?selectContact=contact-0">Richter</a> </td> <td class=""> <a href="...?selectContact=contact-0">Stephan</a> </td> </tr> By clicking on the name, the edit form for Stephan is shown: >>> user.getLink('Richter').click() Note that the row is highlighted now: >>> testing.printElement(user, "//table/tbody/tr[1]") <tr class="selected"><td class="sorted-on"> <a href="...?selectContact=contact-0">Richter</a> </td> <td class=""> <a href="...?selectContact=contact-0">Stephan</a> </td> </tr> After adding a work phone number and deleting one of the two E-mail addresses, >>> user.getControl(name='contact.edit.phones.workPhone.widgets.countryCode')\ ... .value = '+1' >>> user.getControl(name='contact.edit.phones.workPhone.widgets.areaCode')\ ... .value = '555' >>> user.getControl(name='contact.edit.phones.workPhone.widgets.number')\ ... .value = '346-3573' >>> user.getControl('Delete', index=1).click() we now save the contact changes: >>> user.getControl('Apply').click() This submission saves all the data but stays in the edit form of the contact. Only by pressing the "Done" button, the add form will return. >>> user.getControl('Done').click() >>> user.getControl('Add Contact') <SubmitControl name='contact.add.buttons.add' type='submit'> You will also notice that the contact is not highlighted in the table anymore. Let's nwo add a second contact: >>> user.getControl('First Name').value = 'Roger' >>> user.getControl('Last Name').value = 'Ineichen' >>> user.getControl(name='contact.add.phones.homePhone.widgets.countryCode')\ ... .value = '+41' >>> user.getControl(name='contact.add.phones.homePhone.widgets.areaCode')\ ... .value = '43' >>> user.getControl(name='contact.add.phones.homePhone.widgets.number')\ ... .value = '12 23 23' >>> user.getControl('Add Contact').click() You can now sort the contacts by last and first name now, of course. Clicking on the "Last Name" table header cell, will leave the order, since the ordering must be initialized. The second time the order is reversed: >>> user.getLink('Last Name').click() >>> user.getLink('Last Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[1]/a/text()", ... multiple=True, serialize=False) Richter Ineichen Selecting another header will sort on it. Let's choose the first name; clicking on it once sorts it in ascending order: >>> user.getLink('First Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/a/text()", ... multiple=True, serialize=False) Roger Stephan Clicking it again, reverses the order: >>> user.getLink('First Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/a/text()", ... multiple=True, serialize=False) Stephan Roger To delete a contact, you must first select it: >>> user.getLink('Roger').click() At the bototm of the contact form is a delete button that will delete the entire contact: >>> user.getControl('Delete').click() The user is now gone from the table and we are returned to the add form: >>> user.getLink('Roger') Traceback (most recent call last): ... LinkNotFoundError >>> user.getControl('Add Contact') <SubmitControl name='contact.add.buttons.add' type='submit'>
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/README.txt
README.txt
__docformat__ = "reStructuredText" import persistent import zope.interface import zope.location from zope.container import contained, btree from zope.schema.fieldproperty import FieldProperty from z3c.formdemo.addressbook import interfaces class Addresses(btree.BTreeContainer): pass class Address(contained.Contained, persistent.Persistent): zope.interface.implements(interfaces.IAddress) street = FieldProperty(interfaces.IAddress['street']) city = FieldProperty(interfaces.IAddress['city']) state = FieldProperty(interfaces.IAddress['state']) zip = FieldProperty(interfaces.IAddress['zip']) def __init__(self, **data): for name, value in data.items(): setattr(self, name, value) class EMails(zope.location.Location, list): pass class EMail(contained.Contained, persistent.Persistent): zope.interface.implements(interfaces.IEMail) user = FieldProperty(interfaces.IEMail['user']) host = FieldProperty(interfaces.IEMail['host']) def __init__(self, **data): for name, value in data.items(): setattr(self, name, value) @apply def fullAddress(): def get(self): return self.user + u'@' + self.host def set(self, value): self.user, self.host = value.split('@') return property(get, set) class Phone(contained.Contained, persistent.Persistent): zope.interface.implements(interfaces.IPhone) countryCode = FieldProperty(interfaces.IPhone['countryCode']) areaCode = FieldProperty(interfaces.IPhone['areaCode']) number = FieldProperty(interfaces.IPhone['number']) extension = FieldProperty(interfaces.IPhone['extension']) def __init__(self, **data): for name, value in data.items(): setattr(self, name, value) class Contact(contained.Contained, persistent.Persistent): zope.interface.implements(interfaces.IContact) firstName = FieldProperty(interfaces.IContact['firstName']) lastName = FieldProperty(interfaces.IContact['lastName']) birthday = FieldProperty(interfaces.IContact['birthday']) addresses = None emails = None homePhone = None cellPhone = None workPhone = None def __init__(self, **data): # Save all values for name, value in data.items(): setattr(self, name, value)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/addressbook/contact.py
contact.py
__docformat__ = "reStructuredText" from xml.sax.saxutils import quoteattr from zope.app.pagetemplate import ViewPageTemplateFile from zope.session.interfaces import ISession from zc.table import table, column, interfaces class ListFormatter(table.SortingFormatterMixin, table.AlternatingRowFormatter): """Provides a width for each column.""" sortedHeaderTemplate = ViewPageTemplateFile('table_sorted_header.pt') sortKey = 'formdemo.table.sort-on' widths = None columnCSS = None def __init__(self, *args, **kw): # Figure out sorting situation kw['ignore_request'] = True request = args[1] prefix = kw.get('prefix') session = ISession(request)[self.sortKey] if 'sort-on' in request: name = request['sort-on'] if prefix and name.startswith(prefix): name = name[len(prefix):] oldName, oldReverse = session.get(prefix, (None, None)) if oldName == name: session[prefix] = (name, not oldReverse) else: session[prefix] = (name, False) # Now get the sort-on data from the session if prefix in session: kw['sort_on'] = [session[prefix]] super(ListFormatter, self).__init__(*args, **kw) self.columnCSS = {} self.sortOn = (None, None) if 'sort_on' in kw: for name, reverse in kw['sort_on']: self.columnCSS[name] = 'sorted-on' self.sortOn = kw['sort_on'][0] def getHeader(self, column): contents = column.renderHeader(self) if (interfaces.ISortableColumn.providedBy(column)): contents = self._wrapInSortUI(contents, column) return contents def _wrapInSortUI(self, header, column): name = column.name if self.prefix: name = self.prefix + name isSortedOn = self.sortOn[0] == column.name isAscending = self.sortOn[0] == column.name and not self.sortOn[1] isDecending = self.sortOn[0] == column.name and self.sortOn[1] return self.sortedHeaderTemplate( header=header, name=name, isSortedOn=isSortedOn, isAscending=isAscending, isDecending=isDecending) def renderContents(self): """Avoid to render empty table (tr) rows.""" rows = self.renderRows() if not rows: return ' <thead%s>\n%s </thead>\n' % ( self._getCSSClass('thead'), self.renderHeaderRow()) else: return ' <thead%s>\n%s </thead>\n <tbody>\n%s </tbody>\n' % ( self._getCSSClass('thead'), self.renderHeaderRow(), rows) def renderHeader(self, column): width = '' if self.widths: idx = list(self.visible_columns).index(column) width = ' width="%i"' %self.widths[idx] klass = self.cssClasses.get('tr', '') if column.name in self.columnCSS: klass += klass and ' ' or '' + self.columnCSS[column.name] return ' <th%s class=%s>\n %s\n </th>\n' % ( width, quoteattr(klass), self.getHeader(column)) def renderCell(self, item, column): klass = self.cssClasses.get('tr', '') if column.name in self.columnCSS: klass += klass and ' ' or '' + self.columnCSS[column.name] return ' <td class=%s>\n %s\n </td>\n' % ( quoteattr(klass), self.getCell(item, column)) def renderExtra(self): """Avoid use of resourcelibrary in original class.""" return '' class SelectedItemFormatter(ListFormatter): selectedItem = None def renderRow(self, item): self.row += 1 klass = self.cssClasses.get('tr', '') if klass: klass += ' ' if item == self.selectedItem: klass += 'selected' else: klass += self.row_classes[self.row % 2] return ' <tr class=%s>\n%s </tr>\n' % ( quoteattr(klass), self.renderCells(item))
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/browser/formatter.py
formatter.py
__docformat__ = "reStructuredText" import zope.interface from zope.session.interfaces import ISession from z3c.form import button, field, form, interfaces from z3c.formui import layout from zc.table import table, column from z3c.formdemo.browser import formatter from z3c.formdemo.spreadsheet import content class SpreadsheetDataColumn(column.SortingColumn): def __init__(self, field): super(SpreadsheetDataColumn, self).__init__(field.title, field.__name__) def renderCell(self, item, formatter): return item.widgets[self.name].render() def getSortKey(self, item, formatter): return item.widgets[self.name].value class SpreadsheetActionsColumn(column.Column): def __init__(self): super(SpreadsheetActionsColumn, self).__init__( u'Actions', 'actions') def renderCell(self, item, formatter): return '\n'.join( [action.render() for action in item.actions.values()] ) class AddRow(form.AddForm): form.extends(form.AddForm) prefix = 'add.' def __init__(self, spreadsheet): super(AddRow, self).__init__(spreadsheet.context, spreadsheet.request) self.fields = spreadsheet.rowFields self.sessionKey = spreadsheet.sessionKey def create(self, data): return content.Candidate(**data) def add(self, object): count = 0 while 'candidate-%i' %count in self.context: count += 1; self._name = 'candidate-%i' %count self.context[self._name] = object return object def update(self): super(AddRow, self).update() if self._finishedAdd: # Purposefully do not deactivate add-mode, so that multiple # candidates can be added at once. self.request.response.redirect(self.request.getURL()) @button.buttonAndHandler(u'Cancel') def handleCancel(self, action): ISession(self.request)[self.sessionKey]['add'] = False self.request.response.redirect(self.request.getURL()) class EditRow(form.EditForm): def __init__(self, spreadsheet, content): super(EditRow, self).__init__(spreadsheet.context, spreadsheet.request) self.fields = spreadsheet.rowFields self.content = content self.prefix = str(content.__name__) + '.' self.sessionKey = spreadsheet.sessionKey @property def edit(self): name = ISession(self.request)[self.sessionKey].get('edit') return self.content.__name__ == name def getContent(self): return self.content def updateWidgets(self): self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), interfaces.IWidgets) if not self.edit: self.widgets.mode = interfaces.DISPLAY_MODE self.widgets.update() @button.buttonAndHandler(u'Edit', condition=lambda form: not form.edit) def handleEdit(self, action): ISession(self.request)[self.sessionKey]['edit'] = self.content.__name__ self.request.response.redirect(self.request.getURL()) @button.buttonAndHandler(u'Save', condition=lambda form: form.edit) def handleSave(self, action): self.handleApply(self, action) if not self.widgets.errors: ISession(self.request)[self.sessionKey]['edit'] = None self.request.response.redirect(self.request.getURL()) @button.buttonAndHandler(u'Cancel', condition=lambda form: form.edit) def handleCancel(self, action): ISession(self.request)[self.sessionKey]['edit'] = None self.request.response.redirect(self.request.getURL()) class Spreadsheet(layout.FormLayoutSupport, form.Form): sessionKey = 'z3c.formdemo.spreadsheet' rowFields = None columnWidths = None @property def add(self): return ISession(self.request)[self.sessionKey].get('add', False) @button.buttonAndHandler(u'Add', condition=lambda form: not form.add) def handleAdd(self, action): ISession(self.request)[self.sessionKey]['add'] = True self.updateActions() def update(self): super(Spreadsheet, self).update() rows = [] for candidate in self.getContent(): row = EditRow(self, candidate) row.update() rows.append(row) if self.add: row = AddRow(self) row.update() rows.append(row) columns = [SpreadsheetDataColumn(field.field) for field in self.rowFields.values()] columns.append(SpreadsheetActionsColumn()) self.table = formatter.SelectedItemFormatter( self.context, self.request, rows, prefix = self.sessionKey + '.', columns=columns, sort_on=[('lastName', False)]) self.table.sortKey = 'formdemo.spreadsheet.sort-on' self.table.widths = self.columnWidths + (100,)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/spreadsheet/spreadsheet.py
spreadsheet.py
================ Spreadsheet Demo ================ The purpose of the spreadsheet demo is to demonstrate how the form framework can be combined with another framework, in our case the Zope Corp.'s tables. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.handleErrors = False >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "Spreadsheet" link: >>> user.getLink('Spreadsheet').click() There is only one screen for this demo. In it you see the candidate evaluations table: >>> testing.printElement(user, "//h1") <h1>Spreadsheet Demo ...</h1> Initially there are no evaluations, so the screen contains little information. Let's first fill out a few evaluations by clicking on the button below the table. >>> user.getControl('Add').click() Once clicked, the button below the table disappears, and a new row is shown in the table allowing us to add another evaluation. So let's fill out information and add the evaluation: >>> user.getControl(name='add.widgets.lastName').value = u'Richter' >>> user.getControl(name='add.widgets.firstName').value = u'Stephan' >>> user.getControl(name='add.widgets.rating:list').getControl('good').click() >>> user.getControl('Add').click() When the page returns, we see a row with the entry of Stephan Richter, ... >>> testing.printElement(user, "//table/tbody/tr[2]") <tr class="even"><td class="sorted-on"> <span id="candidate-0-widgets-lastName" class="text-widget required textline-field">Richter</span> </td> <td class=""> <span id="candidate-0-widgets-firstName" class="text-widget required textline-field">Stephan</span> </td> <td class=""> <span id="candidate-0-widgets-rating" class="select-widget choice-field"><span class="selected-option">good</span></span> </td> <td class=""> <input ... value="Edit" type="submit" /></td> </tr> ... but also another add evaluation row. This is by design, so that the user can quickly record new entries. So let's add another: >>> user.getControl(name='add.widgets.lastName').value = u'Ineichen' >>> user.getControl(name='add.widgets.firstName').value = u'Roger' >>> user.getControl(name='add.widgets.rating:list')\ ... .getControl('excellent').click() >>> user.getControl('Add').click() We are done now with adding new evaluations. Clicking on the "Cancel" button, removes the add line. >>> user.getControl('Cancel').click() >>> user.getControl(name='add.widgets.lastName') Traceback (most recent call last): ... LookupError: name 'add.widgets.lastName' We can now edit an evaluation by clicking on the row's edit button: >>> user.getControl('Edit', index=1).click() An edit form for this row appears now for Stephan. Let's change his rating to "average": >>> user.getControl(name='candidate-0.widgets.rating:list')\ ... .getControl('average').click() But hitting the "Cancel" button wil ignore the changes and simply return to diaplay the row: >>> user.getControl('Cancel').click() >>> testing.printElement(user, "//table/tbody/tr[2]/td[3]/span/span/text()", ... serialize=False) good Let's now edit the rating for real: >>> user.getControl('Edit', index=1).click() >>> user.getControl(name='candidate-0.widgets.rating:list')\ ... .getControl('average').click() >>> user.getControl('Save').click() Saving the changes also collapses the edit form back into a display form, saving the user from accessive button clicking. Of course, the data is properly stored. >>> testing.printElement(user, "//table/tbody/tr[2]/td[3]/span/span/text()", ... serialize=False) average The real power of integrating the forms into ``zc.table`` is the automtic column sorting feature that comes with the table framework. By default they are sorted by last name: >>> testing.printElement(user, "//table/tbody/tr/td[1]/span/text()", ... multiple=True, serialize=False) Ineichen Richter Clicking on the "Last Name" table header cell, will leave the order, since the ordering must be initialized. The second time the order is reversed: >>> user.getLink('Last Name').click() >>> user.getLink('Last Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[1]/span/text()", ... multiple=True, serialize=False) Richter Ineichen Selecting another header will sort on it. Let's choose the first name; clicking on it once sorts it in ascending order: >>> user.getLink('First Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/span/text()", ... multiple=True, serialize=False) Roger Stephan Clicking it again, reverses the order: >>> user.getLink('First Name').click() >>> testing.printElement(user, "//table/tbody/tr/td[2]/span/text()", ... multiple=True, serialize=False) Stephan Roger Except for the "Actions" column, all headers can be sorted on: >>> user.getLink('Last Name') <Link text='Last Name' url='...lastName'> >>> user.getLink('First Name') <Link text='First Name' url='...firstName'> >>> user.getLink('Rating') <Link text='Rating' url='...rating'> >>> user.getLink('Actions') Traceback (most recent call last): ... LinkNotFoundError
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/spreadsheet/README.txt
README.txt
* @fileoverview Cross browser XMLHttpRequest implementation * Make sure the response set the Header to 'no-cache'. * * @author Roger Ineichen [email protected] * @version Draft, not complete documented */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // public API //---------------------------------------------------------------------------- /** * Construct a new XMLHttp. * @class This is the basic XMLHttp class. * @constructor * @param {string} url URL pointing to the server * @return A new XMLHttp */ function XMLHttp(url) { this.url = url; this.method = 'GET'; this.async = false; this.username = null; this.password = null; this.timeout = null; this.argString = ""; this.parameters = new Array(); this.headers = new Array(); this.headers['Content-Type'] = 'application/x-www-form-urlencoded' /* internal status flags */ this.isAborted = false; this.isLoading = false; this.isLoaded = false; this.isInteractive = false; this.isComplete = false; /* event handlers (attached functions get called if readyState reached) */ this.onLoading = null; // if readyState 1 this.onLoaded = null; // if readyState 2 this.onInteractive = null; // if readyState 3 this.onComplete = null; // if readyState 4 this.onError = null; // if readyState 4 and status != 200 this.onTimeout = null; // if timeout reached this.callback = null; // if readyState 4 and status == 200 this.callbackArgs = null; /* response variables */ this.responseText = null; this.responseXML = null; /* setup the xmlhttp request now */ this.xmlhttp = getXmlHttpRequest() } /** * Set the header information for the XMLHttp instance. * @param {array} args of key, value */ XMLHttp.prototype.setHeaders = function(args) { for (var i in args) { this.headers[i] = args[i]; } } /** * Set the arguments for the request or the XMLHttp instance. * @param {array} args of key, value */ XMLHttp.prototype.setArguments = function(args) { for (var i in args) { // set parameter to the xmlhttp instance or to the parameter array if (typeof(this[i])=="undefined") { this.parameters[i] = args[i]; } else { this[i] = args[i]; } } } /** * Process a 'POST' request. * @param {function} callback callback funtion * @param {array} callbackArgs callback arguments */ XMLHttp.prototype.post = function(callback, callbackArgs) { this.method = 'POST'; this.async = false; if (typeof(callback)=="function") { this.callback = callback; this.async = true } if (typeof(callbackArgs)!="undefined") { this.callbackArgs = callbackArgs; } if (this.async) { this.process(); } else { return this.process(); } } /** * Process a 'GET' request. * @param {function} callback callback funtion * @param {array} callbackArgs callback arguments */ XMLHttp.prototype.get = function(callback, callbackArgs) { this.method = 'GET'; this.async = false; if (typeof(callback)=="function") { this.callback = callback; this.async = true } if (typeof(callbackArgs)!="undefined") { this.callbackArgs = callbackArgs; } if (this.async) { this.process(); } else { return this.process(); } } //---------------------------------------------------------------------------- // helper methods (can be used directly if you need enhanced access, but the // method post and get are the prefered methods for processing a request.) //---------------------------------------------------------------------------- /** @private */ XMLHttp.prototype.process = function() { if (!this.xmlhttp) return false; var self = this; this.xmlhttp.onreadystatechange = function() { if (self.xmlhttp == null) { return; } if (self.xmlhttp.readyState == 1) { self._doLoading(self); } if (self.xmlhttp.readyState == 2) { self._doLoaded(self); } if (self.xmlhttp.readyState == 3) { self._doInteractive(self); } if (self.xmlhttp.readyState == 4) { self._doComplete(self); } }; try { var args = null; for (var i in this.parameters) { if (this.argString.length>0) { this.argString += "&"; } this.argString += encodeURIComponent(i) + "=" + encodeURIComponent(this.parameters[i]); } if (this.method == "GET") { if (this.argString.length>0) { this.url += ((this.url.indexOf("?")>-1)?"&":"?") + this.argString; } this.xmlhttp.open(this.method, this.url, this.async); } if (this.method == "POST") { this.xmlhttp.open(this.method, this.url, this.async, this.username, this.password); args = this.argString; } if (typeof(this.xmlhttp.setRequestHeader)!="undefined" && this.xmlhttp.readyState == 1) { for (var i in this.headers) { this.xmlhttp.setRequestHeader(i, this.headers[i]); } } if (this.timeout > 0) { setTimeout(this._doTimeout, this.timeout); } this.xmlhttp.send(args); } catch(z) { return false; } /* on async call we return false and on sync calls we return the xmlhttp request */ if (this.async) { return false; } else { return this.xmlhttp; } } //---------------------------------------------------------------------------- // helper methods (can be used as a standalone cross browser xmlhttp request) //---------------------------------------------------------------------------- /** * Global helper function for a cross browser XMLHttpRequest object. * @class This is a global helper function for a cross browser XMLHttpRequest object. * @constructor * @return A XMLHttpRequest instance for gecko browsers and a ActiveXObjecct * for ie browsers. Unsuported browsers get null returned. */ getXmlHttpRequest = function() { if (window.XMLHttpRequest) { var req = new XMLHttpRequest(); // some older versions of Moz did not support the readyState property // and the onreadystate event so we patch it! if (req.readyState == null) { req.readyState = 1; req.addEventListener("load", function () { req.readyState = 4; if (typeof req.onreadystatechange == "function") { req.onreadystatechange(); } }, false); } return req; } else if (window.ActiveXObject) { var MSXML_XMLHTTP_IDS = new Array( "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"); var success = false; for (var i = 0; i < MSXML_XMLHTTP_IDS.length && !success; i++) { try { return new ActiveXObject(MSXML_XMLHTTP_IDS[i]); success = true; } catch (e) {} } } else { return null; } } //---------------------------------------------------------------------------- // built in helper methods //---------------------------------------------------------------------------- /** @private */ XMLHttp.prototype._doLoading = function(self) { if (self.isLoading) { return; } if (typeof(self.onLoading)=="function") { self.onLoading(self.xmlhttp); } self.isLoading = true; } /** @private */ XMLHttp.prototype._doLoaded = function(self) { if (self.isLoaded) { return; } if (typeof(self.onLoaded)=="function") { self.onLoaded(self.xmlhttp); } self.isLoaded = true; } /** @private */ XMLHttp.prototype._doInteractive = function(self) { if (self.isInteractive) { return; } if (typeof(self.onInteractive)=="function") { self.onInteractive(self.xmlhttp); } self.isInteractive = true; } /** @private */ XMLHttp.prototype._doComplete = function(self) { if (self.isComplete || self.isAborted) { return; } self.isComplete = true; self.status = self.xmlhttp.status; self.statusText = self.xmlhttp.statusText; self.responseText = self.xmlhttp.responseText; self.responseXML = self.xmlhttp.responseXML; if (typeof(self.onComplete)=="function") { self.onComplete(self.xmlhttp); } if (self.xmlhttp.status==200 && typeof(self.callback)=="function") { if (self.callbackArgs) { self.callback(self.xmlhttp, self.callbackArgs); } else { self.callback(self.xmlhttp); } } if (self.xmlhttp.status!=200 && typeof(self.onError)=="function") { self.onError(self.xmlhttp); } if (self.async) { // on async calls, clean up so IE doesn't leak memory delete self.xmlhttp['onreadystatechange']; self.xmlhttp = null; } } /** @private */ XMLHttp.prototype._doTimeout = function(self) { if (self.xmlhttp!=null && !self.isComplete) { self.xmlhttp.abort(); self.isAborted = true; if (typeof(self.onTimeout)=="function") { self.onTimeout(self.xmlhttp); } // Opera won't fire onreadystatechange after abort, but other browsers do. // So we can't rely on the onreadystate function getting called. Clean up here! delete self.xmlhttp['onreadystatechange']; self.xmlhttp = null; } }
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/skin/xmlhttp.js
xmlhttp.js
* @fileoverview JSON-RPC client implementation * @author Roger Ineichen [email protected] * @version Initial, not documented */ //---------------------------------------------------------------------------- function JSONRPC(url) { this._url = url; this._methods = new Array(); this._user = null; this._password = null; } function getJSONRPCProxy(url) { return new JSONRPC(url); } JSONRPC.prototype.addMethod = function(name, callback, requestId) { if (typeof(requestId) == 'undefined') { requestId = "jsonRequest"; } var self = this; if(!self[name]){ var method = new JSONRPCMethod(this._url, name, callback, requestId, this._user, this._password); self[name] = method; this._methods.push(method); } } JSONRPC.prototype.setAuthentication = function(user, pass) { this._user = user; this._password = pass; for(var i=0;i<this._methods.length;i++){ this._methods[i].setAuthentication(user, pass); } } function JSONRPCMethod(url, methodName, callback, requestId, user, pass) { this.methodName = methodName; this.callback = callback; this.requestId = requestId; this.url = url; this.user = user; this.password = pass; var self = this; var fn = function(){ var args = new Array(); for(var i=0;i<arguments.length;i++){ args.push(arguments[i]); } if(self.callback) { var data = self.jsonRequest(self.requestId, self.methodName, args); self.postData(self.url, self.user, self.password, data, function(resp){ var res = null; var exc =null; try{ res = self.handleResponse(resp); }catch(e){ exc = e; } try{ callback(res, self.requestId, exc); }catch(e){ alert("except callback"); } args = null; resp = null; }); } else{ var data = self.jsonRequest(self.requestId, self.methodName, args); var resp = self.postData(self.url, self.user, self.password, data); return self.handleResponse(resp); } } return fn; } JSONRPCMethod.prototype.postData = function(url, user, pass, data, callback) { var xmlhttp = new XMLHttp(url); var header = new Array() header["Content-Type"] = "application/json-rpc"; xmlhttp.setHeaders(header); xmlhttp.user = user; xmlhttp.password = pass; xmlhttp.argString = data; if(callback == null){ return xmlhttp.post(); }else{ xmlhttp.post(callback); } } JSONRPCMethod.prototype.jsonRequest = function(id, methodName, args){ var ji = toJSON(id); var jm = toJSON(methodName); var ja = toJSON(args); return '{"id":' + ji + ', "method":' + jm + ', "params":' + ja + "}"; } JSONRPCMethod.prototype.setAuthentication = function(user, pass){ this.user = user; this.password = pass; } JSONRPCMethod.prototype.notify = function(){ var args=new Array(); for(var i=0;i<arguments.length;i++){ args.push(arguments[i]); } var data = this.jsonRequest(null, this.methodName, args); this.postData(this.url, this.user, this.password, data, function(resp){}); } JSONRPCMethod.prototype.handleResponse = function(resp){ var status=null; try{ status = resp.status; }catch(e){ } if(status == 200){ var respTxt = ""; try{ respTxt=resp.responseText; }catch(e){ } if(respTxt == null || respTxt == ""){ alert("The server responded with an empty document."); }else{ var res = this.unmarshall(respTxt); if(res.error != null){ alert("error " + res.error); } else if (res.requestId != self.requestId) { alert("wrong json id returned"); } else{ return res.result; } } }else{ alert("error " + status); } } JSONRPCMethod.prototype.unmarshall = function(source){ try { var obj; eval("obj=" + source); return obj; }catch(e){ alert("The server's response could not be parsed."); } } function escapeJSONChar(c) { if(c == "\"" || c == "\\") return "\\" + c; else if (c == "\b") return "\\b"; else if (c == "\f") return "\\f"; else if (c == "\n") return "\\n"; else if (c == "\r") return "\\r"; else if (c == "\t") return "\\t"; var hex = c.charCodeAt(0).toString(16); if(hex.length == 1) return "\\u000" + hex; else if(hex.length == 2) return "\\u00" + hex; else if(hex.length == 3) return "\\u0" + hex; else return "\\u" + hex; } function escapeJSONString(s) { var parts = s.split(""); for(var i=0; i < parts.length; i++) { var c =parts[i]; if(c == '"' || c == '\\' || c.charCodeAt(0) < 32 || c.charCodeAt(0) >= 128) parts[i] = escapeJSONChar(parts[i]); } return "\"" + parts.join("") + "\""; } function toJSON(o) { if(o == null) { return "null"; } else if(o.constructor == String) { return escapeJSONString(o); } else if(o.constructor == Number) { return o.toString(); } else if(o.constructor == Boolean) { return o.toString(); } else if(o.constructor == Date) { return o.valueOf().toString(); } else if(o.constructor == Array) { var v = []; for(var i = 0; i < o.length; i++) v.push(toJSON(o[i])); return "[" + v.join(", ") + "]"; } else { var v = []; for(attr in o) { if(o[attr] == null) v.push("\"" + attr + "\": null"); else if(typeof o[attr] == "function"); // skip else v.push(escapeJSONString(attr) + ": " + toJSON(o[attr])); } return "{" + v.join(", ") + "}"; } }
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/skin/json.js
json.js
__docformat__ = "reStructuredText" import datetime import decimal import zope.interface import zope.schema from zope.schema import vocabulary vocab = vocabulary.SimpleVocabulary([ vocabulary.SimpleVocabulary.createTerm(1, '1', u'One'), vocabulary.SimpleVocabulary.createTerm(2, '2', u'Two'), vocabulary.SimpleVocabulary.createTerm(3, '3', u'Three'), vocabulary.SimpleVocabulary.createTerm(4, '4', u'Four'), vocabulary.SimpleVocabulary.createTerm(5, '5', u'Five') ]) class IObjectSchema(zope.interface.Interface): field1 = zope.schema.TextLine( title=u'Field 1') field2 = zope.schema.Int( title=u'Field 2') class IAllFields(zope.interface.Interface): """An interface containing all possible fields.""" asciiField = zope.schema.ASCII( title=u'ASCII', description=u'This is an ASCII field.', default='This is\n ASCII.') asciiLineField = zope.schema.ASCIILine( title=u'ASCII Line', description=u'This is an ASCII-Line field.', default='An ASCII line.') boolField = zope.schema.Bool( title=u'Boolean', description=u'This is a Bool field.', default=True) checkboxBoolField = zope.schema.Bool( title=u'Boolean (Checkbox)', description=u'This is a Bool field displayed suing a checkbox.', default=True) bytesField = zope.schema.Bytes( title=u'Bytes', description=u'This is a Bytes field.', default='\10\45\n\32', required=False) bytesLineField = zope.schema.BytesLine( title=u'Bytes Line', description=u'This is a bytes line field.', default='A Bytes line.') choiceField = zope.schema.Choice( title=u'Choice', description=u'This is a choice field.', default=3, vocabulary=vocab) optionalChoiceField = zope.schema.Choice( title=u'Choice (Not Required)', description=u'This is a non-required choice field.', vocabulary=vocab, required=False) promptChoiceField = zope.schema.Choice( title=u'Choice (Explicit Prompt)', description=u'This is a choice field with an explicit prompt.', vocabulary=vocab, required=False) dateField = zope.schema.Date( title=u'Date', description=u'This is a Date field.', default=datetime.date(2007, 4, 1)) datetimeField = zope.schema.Datetime( title=u'Date/Time', description=u'This is a Datetime field.', default=datetime.datetime(2007, 4, 1, 12)) decimalField = zope.schema.Decimal( title=u'Decimal', description=u'This is a Decimal field.', default=decimal.Decimal('12.87')) dictField = zope.schema.Dict( title=u'Dictionary', description=u'This is a Dictionary field.', key_type=zope.schema.TextLine(), value_type=choiceField, default={u'a': 1, u'c': 3}) dottedNameField = zope.schema.DottedName( title=u'Dotted Name', description=u'This is a DottedName field.', default='z3c.form') floatField = zope.schema.Float( title=u'Float', description=u'This is a Float field.', default=12.8) frozenSetField = zope.schema.FrozenSet( title=u'Frozen Set', description=u'This is a FrozenSet field.', value_type=choiceField, default=frozenset([1, 3]) ) idField = zope.schema.Id( title=u'Id', description=u'This is a Id field.', default='z3c.form') intField = zope.schema.Int( title=u'Integer', description=u'This is a Int field.', default=12345) listField = zope.schema.List( title=u'List', description=u'This is a List field.', value_type=choiceField, default=[1, 3]) objectField = zope.schema.Object( title=u'Object', description=u'This is an Object field.', schema=IObjectSchema) passwordField = zope.schema.Password( title=u'Password', description=u'This is a Password field.', default=u'mypwd', required=False) setField = zope.schema.Set( title=u'Set', description=u'This is a Set field.', value_type=choiceField, default=set([1, 3]) ) sourceTextField = zope.schema.SourceText( title=u'Source Text', description=u'This is a SourceText field.', default=u'<source />') textField = zope.schema.Text( title=u'Text', description=u'This is a Text field.', default=u'Some\n Text.') textLineField = zope.schema.TextLine( title=u'Text Line', description=u'This is a TextLine field.', default=u'Some Text line.') timeField = zope.schema.Time( title=u'Time', description=u'This is a Time field.', default=datetime.time(12, 0)) timedeltaField = zope.schema.Timedelta( title=u'Time Delta', description=u'This is a Timedelta field.', default=datetime.timedelta(days=3)) tupleField = zope.schema.Tuple( title=u'Tuple', description=u'This is a Tuple field.', value_type=choiceField, default=(1, 3)) uriField = zope.schema.URI( title=u'URI', description=u'This is a URI field.', default='http://zope.org') hiddenField = zope.schema.TextLine( title=u'Hidden Text Line', description=u'This is a hidden TextLine field.', default=u'Some Hidden Text.')
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/widgets/interfaces.py
interfaces.py
__docformat__ = "reStructuredText" import persistent import zope.interface import zope.component from zope.annotation import factory from zope.annotation.interfaces import IAttributeAnnotatable from zope.publisher import browser from zope.schema.fieldproperty import FieldProperty from zope.pagetemplate.interfaces import IPageTemplate from zope.session.interfaces import ISession from z3c.form.interfaces import IWidgets from z3c.form import button, form, field from z3c.form.browser import checkbox from z3c.form.interfaces import HIDDEN_MODE from z3c.formdemo.widgets import interfaces from z3c.template.interfaces import ILayoutTemplate class AllFields(persistent.Persistent): zope.interface.implements(interfaces.IAllFields) zope.component.adapts(IAttributeAnnotatable) asciiField = FieldProperty(interfaces.IAllFields['asciiField']) asciiLineField = FieldProperty(interfaces.IAllFields['asciiLineField']) boolField = FieldProperty(interfaces.IAllFields['boolField']) checkboxBoolField = FieldProperty( interfaces.IAllFields['checkboxBoolField']) bytesField = FieldProperty(interfaces.IAllFields['bytesField']) bytesLineField = FieldProperty(interfaces.IAllFields['bytesLineField']) choiceField = FieldProperty(interfaces.IAllFields['choiceField']) optionalChoiceField = FieldProperty( interfaces.IAllFields['optionalChoiceField']) promptChoiceField = FieldProperty( interfaces.IAllFields['promptChoiceField']) dateField = FieldProperty(interfaces.IAllFields['dateField']) datetimeField = FieldProperty(interfaces.IAllFields['datetimeField']) decimalField = FieldProperty(interfaces.IAllFields['decimalField']) dictField = FieldProperty(interfaces.IAllFields['dictField']) dottedNameField = FieldProperty(interfaces.IAllFields['dottedNameField']) floatField = FieldProperty(interfaces.IAllFields['floatField']) frozenSetField = FieldProperty(interfaces.IAllFields['frozenSetField']) idField = FieldProperty(interfaces.IAllFields['idField']) intField = FieldProperty(interfaces.IAllFields['intField']) listField = FieldProperty(interfaces.IAllFields['listField']) objectField = FieldProperty(interfaces.IAllFields['objectField']) passwordField = FieldProperty(interfaces.IAllFields['passwordField']) setField = FieldProperty(interfaces.IAllFields['setField']) sourceTextField = FieldProperty(interfaces.IAllFields['sourceTextField']) textField = FieldProperty(interfaces.IAllFields['textField']) textLineField = FieldProperty(interfaces.IAllFields['textLineField']) timeField = FieldProperty(interfaces.IAllFields['timeField']) timedeltaField = FieldProperty(interfaces.IAllFields['timedeltaField']) tupleField = FieldProperty(interfaces.IAllFields['tupleField']) uriField = FieldProperty(interfaces.IAllFields['uriField']) hiddenField = FieldProperty(interfaces.IAllFields['hiddenField']) # register the AllField class as a annotation adapter getAllFields = factory(AllFields) class AllFieldsForm(form.EditForm): """A form showing all fields.""" form.extends(form.EditForm) fields = field.Fields(interfaces.IAllFields).omit( 'dictField', 'objectField') fields['checkboxBoolField'].widgetFactory = \ checkbox.SingleCheckBoxFieldWidget buttons = form.EditForm.buttons + \ button.Buttons( button.ImageButton(name='pressme', image=u'pressme.png') ) label = 'Widgets Demo' @button.handler(buttons['pressme']) def handlePressMe(self, action): self.status = u'Press me was clicked!' def getContent(self): return interfaces.IAllFields(self.context) def updateWidgets(self): self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.update() self.widgets['hiddenField'].mode = HIDDEN_MODE self.widgets['promptChoiceField'].prompt = True self.widgets['promptChoiceField'].update() def __call__(self): self.update() layout = zope.component.getMultiAdapter((self, self.request), ILayoutTemplate) return layout(self)
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/widgets/browser.py
browser.py
============ Widgets Demo ============ The purpose of the widgets demo is demonstrate that there exists a widget for each standard field type and how it works. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "All widgets" link: >>> user.getLink('All widgets').click() You are now in the widgets form. Let's now fill out all forms an submit the form: >>> import cStringIO >>> def addSelection(browser, name, value, selected=True): ... form = browser.mech_browser.forms().next() ... form.new_control( ... 'select', name, attrs={'__select': {'name': name, 'size': '5'}}) ... form.new_control( ... 'select', name, ... attrs={'__select': {'name': name, 'size': '5'}, ... 'selected': 'selected', 'value': value}) >>> user.getControl('ASCII', index=0).value += u' Add on.' >>> user.getControl('ASCII Line').value += u' Add on.' >>> user.getControl(name='form.widgets.boolField:list')\ ... .getControl(value='false').click() # Boolean >>> user.getControl('Bytes', index=0).add_file( ... cStringIO.StringIO('File contents'), 'text/plain', 'test.txt') >>> user.getControl('Bytes Line').value += u' Add on.' >>> user.getControl('Choice', index=0).getControl('Two').click() >>> user.getControl('Choice (Not Required)').getControl('Two').click() >>> user.getControl('Choice (Explicit Prompt)').getControl('Two').click() >>> user.getControl('Date', index=0).value = u'7/1/07' >>> user.getControl('Date/Time').value = u'7/1/07 12:15 AM' >>> user.getControl('Decimal').value = u'12439.986' >>> user.getControl('Dotted Name').value += u'demo' >>> user.getControl('Float').value = u'12439.986' >>> user.getControl('Frozen Set').getControl('One').click() >>> user.getControl('Id').value += u'demo' >>> user.getControl('Integer').value = u'12439' >>> addSelection(user, 'form.widgets.listField', u'1') >>> user.getControl('Password').value = u'pwd' >>> user.getControl('Set', index=1).getControl('One').click() >>> user.getControl('Source Text').value += u' Add on.' >>> user.getControl('Text', index=1).value += u' Add on.' >>> user.getControl('Text Line').value += u' Add on.' >>> user.getControl('Time', index=1).value = u'12:15 AM' >>> user.getControl('Time Delta').value = u'4 days, 1:00:00' >>> addSelection(user, 'form.widgets.tupleField', u'1') >>> user.getControl('URI').value += u'/Documentation' >>> user.getControl(name='form.widgets.hiddenField').value += u' Add on.' >>> user.getControl('Apply').click() Once submitted, the same form returns with a data changed method: >>> from z3c.formdemo import testing >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Data successfully updated.</div> Let's now ensure that the data has been truly uploaded: >>> from z3c.formdemo.widgets import interfaces >>> fields = interfaces.IAllFields(getRootFolder()) >>> fields.asciiField 'This is\r\n ASCII. Add on.' >>> fields.asciiLineField 'An ASCII line. Add on.' >>> fields.boolField False >>> fields.bytesField 'File contents' >>> fields.bytesLineField 'A Bytes line. Add on.' >>> fields.choiceField 2 >>> fields.optionalChoiceField 2 >>> fields.promptChoiceField 2 >>> fields.dateField datetime.date(2007, 7, 1) >>> fields.datetimeField datetime.datetime(2007, 7, 1, 0, 15) >>> fields.decimalField Decimal("12439.986") >>> fields.dottedNameField 'z3c.formdemo' >>> fields.floatField 12439.986000000001 >>> fields.frozenSetField frozenset([3]) >>> fields.idField 'z3c.formdemo' >>> fields.intField 12439 >>> fields.listField [1] >>> fields.passwordField u'pwd' >>> fields.setField set([3]) >>> fields.sourceTextField u'<source /> Add on.' >>> fields.textField u'Some\r\n Text. Add on.' >>> fields.textLineField u'Some Text line. Add on.' >>> fields.timeField datetime.time(0, 15) >>> fields.timedeltaField datetime.timedelta(4, 3600) >>> fields.tupleField (1,) >>> fields.uriField 'http://zope.org/Documentation' >>> fields.hiddenField u'Some Hidden Text. Add on.' We also have an image button, that can be clicked: >>> user.getControl(name='form.buttons.pressme').click() >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Press me was clicked!</div>
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/widgets/README.txt
README.txt
======================== Hello World Message Demo ======================== The "Hello World Message" demo is intended to demonstrate the most minimal setup required to get add, edit and display to work. To start, we need to open a browser and go to the demo applications overview screen: >>> from z3c.formdemo import testing >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost:8080') Since all demos are purely public, there is no need to log in. Let's now click on the "Hello World" link: >>> user.getLink('Hello World').click() You are now represented with the message add form. >>> user.url 'http://localhost:8080/addHelloWorld.html' If we submit the form by clicking on add, ... >>> user.getControl('Add').click() ... the same page returns telling us we have some errors: >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">There were some errors.</div> This is because we forgot to enter the "Who" field, which is required: >>> testing.printElement(user, "//ul[@class='errors']/li") <li> Who: <div class="error">Required input is missing.</div> </li> Let's now fill out all the required fields and try to add the message again: >>> user.getControl('Who').value = u'Stephan' >>> user.getControl('When').value = u'7/1/07' >>> user.getControl('Add').click() Once submitted, the message is now added to the database and the display view is shown: >>> testing.printElement(user, "//h1") <h1> A <span id="form-widgets-what" class="select-widget required choice-field"><span class="selected-option">cool</span></span> Hello World from <span id="form-widgets-who" class="text-widget required textline-field">Stephan</span> <BLANKLINE> on <span id="form-widgets-when" class="text-widget required date-field">7/1/07</span> ! </h1> The message's edit form can be accessed by clicking on the "Edit Message" link: >>> user.getLink('Edit Message').click() When immediately pressing "Apply", a message appears telling us that no data has been changed: >>> user.getControl('Apply', index=0).click() >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">No changes were applied.</div> Let's now change the name and submit the form: >>> user.getControl('Who').value = u'Roger' >>> user.getControl('Apply', index=0).click() The page now informs us that the data has been updated: >>> testing.printElement(user, "//div[@class='summary']") <div class="summary">Data successfully updated.</div> When pressing the "Apply and View" button, the changed data is stored and the user is also forwarded to the view page again: >>> user.getControl('What').getControl('best').click() >>> user.getControl('Apply and View').click() Of course, the view shows the latest data: >>> testing.printElement(user, "//h1") <h1> A <span id="form-widgets-what" class="select-widget required choice-field"><span class="selected-option">best</span></span> Hello World from <span id="form-widgets-who" class="text-widget required textline-field">Roger</span> <BLANKLINE> on <span id="form-widgets-when" class="text-widget required date-field">7/1/07</span> ! </h1>
z3c.formdemo
/z3c.formdemo-2.1.1.tar.gz/z3c.formdemo-2.1.1/src/z3c/formdemo/message/README.txt
README.txt
__docformat__ = "reStructuredText" import cStringIO import compiler import inspect import sys import zope.component import zope.interface from zope.viewlet import viewlet from zope.publisher.interfaces.browser import IBrowserRequest from z3c.formjs import interfaces class JSFunction(object): zope.interface.implements(interfaces.IJSFunction) def __init__(self, namespace, function): self.namespace = namespace self.function = function @property def name(self): return self.function.func_name @property def arguments(self): args = inspect.getargspec(self.function)[0] if args[0] is 'self': del args[0] return args def render(self): return self.function(*[x for x in ['self'] + self.arguments]) def call(self, *args): sargs = [] for arg in args: argtype = type(arg) if argtype is unicode: sargs.append(repr(arg)[1:]) elif argtype is bool: sargs.append(repr(arg).lower()) elif argtype in (int, float, str): sargs.append(repr(arg)) else: sargs.append(repr(str(arg))) caller = self.name if self.namespace: caller = '%s.%s' % (self.namespace, self.name) return '%s(%s);' % (caller, ','.join(sargs)) def __repr__(self): return '<%s %s>' % ( self.__class__.__name__, self.name) class JSFunctions(object): zope.interface.implements(interfaces.IJSFunctions) def __init__(self): self._functions = {} def add(self, jsFunction, namespace=''): ns = self._functions.setdefault(namespace, []) ns.append(jsFunction) return jsFunction def render(self): result = '' # Render non-namespaced functions for func in self._functions.get('', []): args = func.arguments result += 'function %s(%s) {\n' %( func.name, ', '.join(args) ) code = func.render() result += ' ' + code.replace('\n', '\n ') + '\n' result += '}\n' # Render namespaced functions for ns, funcs in self._functions.items(): if ns == '': continue result += 'var %s = {\n' %ns for func in funcs: args = func.arguments result += ' %s: function(%s) {\n' %( func.name, ', '.join(args) ) code = func.render() result += ' ' + code.replace('\n', '\n ') + '\n' result += ' },\n' result = result[:-2] + '\n' result += '}\n' return result def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self._functions) def function(namespace=''): """A decorator for defining a javascript function.""" def createFunction(func): frame = sys._getframe(1) f_locals = frame.f_locals funcs = f_locals.setdefault('jsFunctions', JSFunctions()) jsFunction = JSFunction(namespace, func) return funcs.add(jsFunction, namespace) return createFunction class JSFunctionsViewlet(viewlet.ViewletBase): """An viewlet for the JS viewlet manager rendering functions.""" zope.component.adapts( zope.interface.Interface, IBrowserRequest, interfaces.IHaveJSFunctions, zope.interface.Interface) def render(self): content = self.__parent__.jsFunctions.render() return u'<script type="text/javascript">\n%s\n</script>' % content
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jsfunction.py
jsfunction.py
__docformat__ = "reStructuredText" import zope.interface import zope.schema from zope.viewlet.interfaces import IViewletManager from z3c.form.interfaces import IButton, IButtonHandler, IManager, IWidget from z3c.form.interfaces import ISelectionManager, IForm # -----[ Event Subscription ]------------------------------------------------ class IJSEvent(zope.interface.Interface): """An interface for javascript event objects.""" name = zope.schema.TextLine( title=u"Event Name", description=u"The name of an event (i.e. click/dblclick/changed).", required=True) class ISelector(zope.interface.Interface): """An object describing the selection of DOM Elements.""" class IIdSelector(ISelector): """Select a DOM element by Id.""" id = zope.schema.TextLine( title=u"Id", description=u"Id of the DOM element to be selected.", required=True) class ICSSSelector(ISelector): """Select a DOM element by a CSS selector expression.""" expr = zope.schema.TextLine( title=u"Expression", description=u"CSS selector pointing to a DOM element.", required=True) class IJSSubscription(zope.interface.Interface): """A Subscription within Javascript.""" event = zope.schema.Object( title=u"Event", description=u"The event.", schema = IJSEvent, required=True) selector = zope.schema.Object( title=u"Selector", description=u"The DOM element selector.", schema = ISelector, required=True) handler = zope.schema.Field( title=u"Handler", description=(u"A callable nneding three argument: event, selector, " u"and request."), required=True) class IJSSubscriptions(zope.interface.Interface): """A manager of Javascript event subscriptions.""" def subscribe(event, selector, handler): """Subscribe an event for a DOM element executing the handler's result.""" def __iter__(): """Return an iterator of all subscriptions.""" def __getitem__(name): """Return all the subscriptions for the handler with the given name.""" class IRenderer(zope.interface.Interface): """Render a component in the intended output format.""" def update(): """Update renderer.""" def render(): """Render content.""" # -----[ Javascript Functions ]---------------------------------------------- class IJSFunction(zope.interface.Interface): """A Javascript Function.""" name = zope.schema.BytesLine( title=u"Name", description=u"The name of the function.", required=True) arguments = zope.schema.List( title=u"Arguments", description=u"A list of arguments of the function.", required=True) def render(): """Render the content of the JS function.""" def call(): """Render a JavaScript call to the function.""" class IJSFunctions(zope.interface.Interface): """A manager of Javascript functions.""" def add(function, namespace=''): """Add a new function to the given namespace.""" def render(self): """Render all functions.""" class IHaveJSFunctions(zope.interface.Interface): """An component that has a JS functions manager . This component is most often a view component. When rendering a page this interface is used to check whether any functions must be rendered. """ jsFunctions = zope.schema.Object( title=u"Javascript Functions", description=u"Attribute holding the JS Functions Manager.", schema = IJSFunctions, required=True) # -----[ JavaScript Viewlet Manager ]----------------------------------------- class IDynamicJavaScript(IViewletManager): """Viewlet manager for dynamically generated javascript.""" # -----[ Widgets ]------------------------------------------------------------ class IWidgetSelector(ISelector): """Select a DOM element using the action.""" action = zope.schema.Field( title=u"Action", description=u"The action being selected.", required=True) # -----[ Views and Forms ]---------------------------------------------------- class IHaveJSSubscriptions(zope.interface.Interface): """An component that has a subscription manager . This component is most often a view component. When rendering a page this interface is used to check whether any subscriptions must be rendered. """ jsSubscriptions = zope.schema.Object( title=u"Javascript Subscriptions", description=u"Attribute holding the JS Subscription Manager.", schema = IJSSubscriptions, required=True) # -----[ Buttons and Handlers ]---------------------------------------------- class IJSButton(IButton): """A button that just connects to javascript handlers.""" class IJSEventHandler(zope.interface.Interface): """An action handler of Javascript events for fields and buttons.""" __name__ = zope.schema.ASCIILine( title=u"Name", description=u"The name of the handler. Like a function's name", required=True) def __call__(event, selector, request): """Call the handler. The result should be a string containing the script to be executed when the event occurs on the specified DOM element. The event *must* provide the ``IJSEvent`` interface. The selector *must* be an ``IWidgetSelector`` component. """ class IJSEventHandlers(zope.interface.Interface): """Javascript event handlers for fields and buttons.""" def addHandler(field, event, handler): """Add a new handler for the fiven field and event specification. The ``field`` and ``event`` arguments can either be instances, classes or specifications/interfaces. The handler *must* provide the ``IJSEventHandler`` interface. """ def getHandlers(field): """Get a list of (event, handler) pairs for the given field. The event is a component providing the ``IJSEvent`` interface, and the handler is the same component that has been added before. """ def copy(): """Copy this object and return the copy.""" def __add__(other): """Add another handlers object. During the process a copy of the current handlers object should be created and the other one is added to the copy. The return value is the copy. """ # -----[ Validator ]-------------------------------------------------------- class IValidationScript(zope.interface.Interface): """Component that renders the script doing the validation.""" def render(): """Render the js expression.""" class IMessageValidationScript(IValidationScript): """Causes a message to be returned at validation.""" class IAJAXValidator(zope.interface.Interface): """A validator that sends back validation data sent from an ajax request.""" ValidationScript = zope.schema.Object( title=u"Validation Script", schema=IValidationScript) def validate(): """Return validation data.""" # -----[ Widget Mode Switcher ]----------------------------------------------- class IWidgetModeSwitcher(zope.interface.Interface): """A component that enables forms to switch between display and input widgets.""" def getDisplayWidget(): """Return the rendered display widget. The method expects to find a field called 'widget-name' in the request containing the short name to the field/widget. """ def getInputWidget(): """Return the rendered input widget. The method expects to find a field called 'widget-name' in the request containing the short name to the field/widget. """ def saveWidgetValue(): """Save the new value of the widget and return any possible errors. The method expects to find a field called 'widget-name' in the request containing the short name to the field/widget. The request must also contain all fields required for the widget to successfully extract the value. """ class IWidgetSwitcher(zope.interface.Interface): """Switches the widhet to another mode.""" form = zope.schema.Field( title=u"Form", description=u"The form.", required=True) widget = zope.schema.Field( title=u"Widget", description=u"The widget that is being switched.", required=True) mode = zope.schema.TextLine( title=u"Mode", description=u"The mode to which to switch to.", required=True) def render(): """Render the switcher into JavaScript.""" class ILabelWidgetSwitcher(zope.interface.Interface): """Switches the widget to an input widget when clicking on the label.""" form = zope.schema.Field( title=u"Form", description=u"The form.", required=True) mode = zope.schema.TextLine( title=u"Mode", description=u"The mode to which to switch to.", required=True) def render(): """Render the switcher into JavaScript.""" class IWidgetSaver(zope.interface.Interface): """Saves a widget's value to the server.""" form = zope.schema.Field( title=u"Form", description=u"The form.", required=True) widget = zope.schema.Field( title=u"Widget", description=u"The widget for which the value is saved.", required=True) def render(): """Render the saver into JavaScript.""" # -----[ AJAX ]-------------------------------------------------------- class IAJAXHandlers(ISelectionManager): """Container of AJAX handlers.""" class IAJAXHandler(zope.interface.Interface): def __call__(context, request): """Return a callable that calls the handler function. Return a callable which has access to context and request without context and request being passed as arguments. """ class IAJAXRequestHandler(zope.interface.Interface): """An object that has methods for handling ajax requests.""" ajaxRequestHandlers = zope.schema.Object( title=u"AJAX Request Handlers Manager", schema=IAJAXHandlers) # -----[ Form Traverser ]------------------------------------------------- class IFormTraverser(zope.interface.Interface): """Marker interface for forms that can be traversed by the @@ajax view.""" # -----[ Client Side Event System ]--------------------------------------- class IClientEventHandlers(zope.interface.Interface): """A collection of client side event handlers for server side events.""" def addHandler(required, handler): """Add a new handler for a the given required interfaces.""" def getHandler(event): """Get the handler for the given server side event.""" def copy(): """Copy this object and return the copy.""" def __add__(other): """Add another handlers object. During the process a copy of the current handlers object should be created and the other one is added to the copy. The return value is the copy. """ class IClientEventHandler(zope.interface.Interface): """A handler managed by the client event handlers.""" def __call__(self, form, event): """Execute the handler."""
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/interfaces.py
interfaces.py
=========================== Form Javascript Integration =========================== This package is designed to provide a Python API to common Javascript features for forms written with the ``z3c.form*`` packages. While the reference backend-implementation is for the JQuery library, any other Javascript library can be hooked into the Python API. The documents are ordered in the way they should be read: - ``jsaction.txt`` [must read] This document describes how JS scripts can be connected to events on a any widget, inclduing buttons. - ``jsvalidator.txt`` [must read] This document demonstrates how "live" widget value validation can be achieved. - ``jsevent.txt`` [advanced users] This documents describes the generalization that allows hooking up script to events on any field. - ``jqueryrenderer.txt`` [advanced users] This document demonstrates all necessary backend renderer components necessary to accomplish any of the features of this package.
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/README.txt
README.txt
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema.interfaces from z3c.form import button from z3c.form.interfaces import IWidgets, DISPLAY_MODE from zope.publisher.interfaces import NotFound from z3c.formjs import ajax, interfaces, jsevent, jsaction class WidgetSwitcher(object): zope.interface.implements(interfaces.IWidgetSwitcher) def __init__(self, form, widget, mode): self.form = form self.widget = widget self.mode = mode def render(self): renderer = zope.component.getMultiAdapter( (self, self.form.request), interfaces.IRenderer) return renderer.render() class LabelWidgetSwitcher(object): zope.interface.implements(interfaces.ILabelWidgetSwitcher) def __init__(self, request, mode): self.request = request self.mode = mode def render(self): renderer = zope.component.getMultiAdapter( (self, self.request), interfaces.IRenderer) return renderer.render() class WidgetSaver(object): zope.interface.implements(interfaces.IWidgetSaver) switcherClass = WidgetSwitcher def __init__(self, form, widget): self.form = form self.widget = widget self.switcher = self.switcherClass(form, widget, DISPLAY_MODE) def render(self): renderer = zope.component.getMultiAdapter( (self, self.form.request), interfaces.IRenderer) return renderer.render() class WidgetModeSwitcher(ajax.AJAXRequestHandler): """A mix-in to forms to allow switching between widget modes.""" zope.interface.implements(interfaces.IWidgetModeSwitcher, interfaces.IHaveJSSubscriptions) buttons = button.Buttons() mode = DISPLAY_MODE @jsaction.handler(zope.schema.interfaces.IField, jsevent.CLICK) def switchToInputWidget(self, event, selector): return WidgetSwitcher(self, selector.widget, 'input').render() @jsaction.handler(zope.schema.interfaces.IField, jsevent.BLUR) def saveWidgetValue(self, event, selector): return WidgetSaver(self, selector.widget).render() @jsevent.subscribe(jsevent.CSSSelector('label'), jsevent.CLICK) def labelClickSwitchesToInputWidget(event, selector, request): return LabelWidgetSwitcher(request, 'input').render() def _getWidget(self, mode): """Get the widget in the given mode.""" # There are two possibilities to extract the wdget, either by widget # short name or by widget id. The latter is significantly more # inefficient, but needed. if 'widget-id' in self.request.form: # Step 1: Determine the full name of the widget name = self.request.form['widget-id'].replace('-', '.') # Step 2: Limit the form fields only to this one widget. # Note: This algorithm might not be fully reliable, but should # work for now. for shortName in self.fields: if name.endswith(shortName): break else: # Step 1: Determine the name of the widget. shortName = self.request.form['widget-name'] # Step 2: Limit the form fields only to this one widget. self.fields = self.fields.select(shortName) # Step 3: Instantiate the widget manager, set the correct mode and # update it. self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), IWidgets) # Step 3: Instantiate the widget manager, set the correct mode and # update it. self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.mode = mode self.widgets.update() # Step 4: Return the widget. return self.widgets[shortName] @ajax.handler def getDisplayWidget(self): '''See interfaces.IWidgetModeSwitcher''' widget = self._getWidget('display') handlers = dict(widget.form.jshandlers.getHandlers(widget.field)) code = handlers[jsevent.CLICK]( jsevent.CLICK, jsaction.WidgetSelector(widget), self.request) widget.onclick = unicode(code.replace('\n', ' ')) return widget.render() @ajax.handler def getInputWidget(self): '''See interfaces.IWidgetModeSwitcher''' widget = self._getWidget('input') handlers = dict(widget.form.jshandlers.getHandlers(widget.field)) code = handlers[jsevent.BLUR]( jsevent.BLUR, jsaction.WidgetSelector(widget), self.request) widget.onblur = unicode(code.replace('\n', ' ')) return widget.render() @ajax.handler def saveWidgetValue(self): '''See interfaces.IWidgetModeSwitcher''' widget = self._getWidget('input') data, errors = self.extractData() if errors: return errors[0].message self.applyChanges(data) return ''
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jsswitch.py
jsswitch.py
__docformat__ = "reStructuredText" import zope.component import zope.interface from zope.traversing.browser import absoluteURL from jquery.layer import IJQueryJavaScriptBrowserLayer from z3c.formjs import interfaces class JQueryIdSelectorRenderer(object): zope.interface.implements(interfaces.IRenderer) zope.component.adapts( interfaces.IIdSelector, IJQueryJavaScriptBrowserLayer) def __init__(self, selector, request): self.selector = selector def update(self): pass def render(self): return u'#' + self.selector.id class JQueryCSSSelectorRenderer(object): zope.interface.implements(interfaces.IRenderer) zope.component.adapts( interfaces.ICSSSelector, IJQueryJavaScriptBrowserLayer) def __init__(self, selector, request): self.selector = selector def update(self): pass def render(self): return self.selector.expr class JQuerySubscriptionRenderer(object): zope.interface.implements(interfaces.IRenderer) zope.component.adapts( interfaces.IJSSubscription, IJQueryJavaScriptBrowserLayer) def __init__(self, subscription, request): self.subscription = subscription self.request = request def update(self): self.selectorRenderer = zope.component.getMultiAdapter( (self.subscription.selector, self.request), interfaces.IRenderer) self.selectorRenderer.update() def render(self): return u'$("%s").bind("%s", function(event){%s});' %( self.selectorRenderer.render(), self.subscription.event.name, self.subscription.handler( self.subscription.event, self.subscription.selector, self.request) ) class JQuerySubscriptionsRenderer(object): zope.interface.implements(interfaces.IRenderer) zope.component.adapts( interfaces.IJSSubscriptions, IJQueryJavaScriptBrowserLayer) def __init__(self, manager, request): self.manager = manager self.request = request def update(self): self.renderers = [] for subscription in self.manager: renderer = zope.component.getMultiAdapter( (subscription, self.request), interfaces.IRenderer) renderer.update() self.renderers.append(renderer) def render(self): return '$(document).ready(function(){\n %s\n})' %( '\n '.join([r.render() for r in self.renderers]) ) class JQueryMessageValidationScriptRenderer(object): zope.component.adapts( interfaces.IMessageValidationScript, IJQueryJavaScriptBrowserLayer) zope.interface.implements(interfaces.IRenderer) function = 'applyErrorMessage' def __init__(self, script, request): self.context = script self.request = request def _ajaxURL(self): widget = self.context.widget form = self.context.form # build js expression for extracting widget value valueString = '$("#%s").val()' % widget.id # build a js expression that joins valueString expression queryString = '"?widget-name=%s&%s=" + %s' % ( widget.__name__, widget.name, valueString) # build a js expression that joins form url, validate path, and query # string ajaxURL = '"'+form.request.getURL() + '/@@ajax/validate" + ' \ + queryString return ajaxURL def update(self): pass def render(self): ajaxURL = self._ajaxURL() # build a js expression that shows the user the error message widget = self.context.widget messageSetter = '%s("%s", msg)' % (self.function, widget.id) ajax = '$.get(%s,\nfunction(msg){%s}\n)' % (ajaxURL, messageSetter) return ajax class JQueryWidgetSwitcherRenderer(object): zope.component.adapts( interfaces.IWidgetSwitcher, IJQueryJavaScriptBrowserLayer) zope.interface.implements(interfaces.IRenderer) function = 'switchWidget' def __init__(self, switcher, request): self.context = switcher self.request = request def _ajaxURL(self): widget = self.context.widget form = self.context.form # build a js expression that joins valueString expression queryString = '?widget-name=%s' % widget.__name__ mode = self.context.mode.title() # build a js expression that joins form url, validate path, and query # string ajaxURL = '"'+ absoluteURL(form, form.request) + '/@@ajax/get' \ + mode + 'Widget' + queryString + '"' return ajaxURL def update(self): pass def render(self): ajaxURL = self._ajaxURL() widget = self.context.widget switcherCall = '%s("%s", "%s", html)' % ( self.function, widget.id, self.context.mode) return '$.get(%s,\nfunction(html){%s}\n)' % (ajaxURL, switcherCall) class JQueryLabelWidgetSwitcherRenderer(object): zope.component.adapts( interfaces.ILabelWidgetSwitcher, IJQueryJavaScriptBrowserLayer) zope.interface.implements(interfaces.IRenderer) function = 'switchWidget' widgetIdExpr = 'event.target.parentNode.attributes["for"].value' def __init__(self, switcher, request): self.context = switcher self.request = request def _ajaxURL(self): # build a js expression that joins valueString expression queryString = '?widget-id=' + self.widgetIdExpr mode = self.context.mode.title() # build a js expression return '"%s/@@ajax/get%sWidget?widget-id=" + %s' % ( self.request.getURL(), mode, self.widgetIdExpr) def update(self): pass def render(self): ajaxURL = self._ajaxURL() switcherCall = '%s(%s, "%s", html)' % ( self.function, self.widgetIdExpr, self.context.mode) return '$.get(%s,\nfunction(html){%s}\n)' % (ajaxURL, switcherCall) class JQueryWidgetSaverRenderer(object): zope.component.adapts( interfaces.IWidgetSaver, IJQueryJavaScriptBrowserLayer) zope.interface.implements(interfaces.IRenderer) function = 'saveWidget' def __init__(self, switcher, request): self.context = switcher self.request = request def _ajaxURL(self): widget = self.context.widget form = self.context.form # build js expression for extracting widget value valueString = '$("#%s").val()' % widget.id # build a js expression that joins valueString expression queryString = '?widget-name=%s&%s=" + %s' % ( widget.__name__, widget.name, valueString) # build a js expression that joins form url, validate path, and query # string ajaxURL = '"'+ absoluteURL(form, form.request) + \ '/@@ajax/saveWidgetValue' + queryString return ajaxURL def update(self): pass def render(self): ajaxURL = self._ajaxURL() widget = self.context.widget saveCall = '%s("%s", msg)' % (self.function, widget.id) switchCall = 'if (error == false) {%s}' %self.context.switcher.render() return '$.get(%s,\nfunction(msg){error=%s; %s}\n)' % ( ajaxURL, saveCall, switchCall)
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jqueryrenderer.py
jqueryrenderer.py
__docformat__ = "reStructuredText" import sys import zope.component import zope.interface import zope.location from zope.interface import adapter from z3c.form import button, action, util from z3c.form.browser.button import ButtonWidget from z3c.form.interfaces import IField, IFieldWidget from z3c.form.interfaces import IFormLayer, IFormAware from z3c.form.interfaces import IButtonAction, IAfterWidgetUpdateEvent from z3c.formjs import interfaces, jsevent class WidgetSelector(jsevent.IdSelector): zope.interface.implements(interfaces.IWidgetSelector) def __init__(self, widget): self.widget = widget @property def id(self): return self.widget.id class JSButton(button.Button): """A simple javascript button in a form.""" zope.interface.implements(interfaces.IJSButton) class JSButtonAction(action.Action, ButtonWidget, zope.location.Location): """A button action specifically for JS buttons.""" zope.interface.implements(IButtonAction) zope.component.adapts(IFormLayer, interfaces.IJSButton) def __init__(self, request, field): action.Action.__init__(self, request, field.title) ButtonWidget.__init__(self, request) self.field = field @property def accesskey(self): return self.field.accessKey @property def value(self): return self.title @property def id(self): return self.name.replace('.', '-') class JSHandlers(object): """Advanced Javascript event handlers for fields and buttons. This implementation of the Javascript event handlers interface used an adapter registry to manage more general versus more specific handler registrations. When asked for handlers, the registry will always return the most specific one for each event. """ zope.interface.implements(interfaces.IJSEventHandlers) def __init__(self): self._registry = adapter.AdapterRegistry() self._handlers = () def addHandler(self, field, event, handler): """See interfaces.IJSEventHandlers""" # Create a specification for the field and event fieldSpec = util.getSpecification(field) eventSpec = util.getSpecification(event) if isinstance(fieldSpec, util.classTypes): fieldSpec = zope.interface.implementedBy(fieldSpec) if isinstance(eventSpec, util.classTypes): eventSpec = zope.interface.implementedBy(eventSpec) # Register the handler self._registry.register( (fieldSpec, eventSpec), interfaces.IJSEventHandler, '', handler) self._handlers += ((field, event, handler),) def getHandlers(self, field): """See interfaces.IJSEventHandlers""" fieldProvided = zope.interface.providedBy(field) handlers = () for event in jsevent.EVENTS: eventProvided = zope.interface.providedBy(event) handler = self._registry.lookup( (fieldProvided, eventProvided), interfaces.IJSEventHandler) if handler: handlers += ((event, handler),) return handlers def copy(self): """See interfaces.IJSEventHandlers""" handlers = JSHandlers() for field, event, handler in self._handlers: handlers.addHandler(field, event, handler) return handlers def __add__(self, other): """See interfaces.IJSEventHandlers""" if not isinstance(other, JSHandlers): raise NotImplementedError handlers = self.copy() for field, event, handler in other._handlers: handlers.addHandler(field, event, handler) return handlers def __repr__(self): return '<%s %r>' % (self.__class__.__name__, [handler for f, e, handler in self._handlers]) class JSHandler(object): zope.interface.implements(interfaces.IJSEventHandler) def __init__(self, func): self.func = func # XXX: should this ever be passed a string? # it is passed a string in unit tests, but I # think we may want to make that an invalid operation. if type(func) == str: self.__name__ = func else: self.__name__ = func.__name__ def __call__(self, event, selector, request): return self.func(selector.widget.form, event, selector) def __repr__(self): return '<%s %r>' %(self.__class__.__name__, self.func) def handler(field, event=jsevent.CLICK): """A decorator for defining a javascript event handler.""" # As a convenience, we also accept form fields to the handler, but get the # real field immediately if IField.providedBy(field): field = field.field def createHandler(func): handler = JSHandler(func) frame = sys._getframe(1) f_locals = frame.f_locals handlers = f_locals.setdefault('jshandlers', JSHandlers()) handlers.addHandler(field, event, handler) return func return createHandler def buttonAndHandler(title, **kwargs): # Add the title to button constructor keyword arguments kwargs['title'] = title # Extract directly provided interfaces: provides = kwargs.pop('provides', ()) # Create button and add it to the button manager factory = kwargs.pop('factory', JSButton) jsButton = factory(**kwargs) zope.interface.alsoProvides(jsButton, provides) frame = sys._getframe(1) f_locals = frame.f_locals buttons = f_locals.setdefault('buttons', button.Buttons()) f_locals['buttons'] += button.Buttons(jsButton) # Return the handler decorator return handler(jsButton) @zope.interface.implementer(zope.interface.Interface) @zope.component.adapter(IAfterWidgetUpdateEvent) def createSubscriptionsForWidget(event): widget = event.widget # Only react to widgets that have a field and know the form. if not (IFieldWidget.providedBy(widget) and IFormAware.providedBy(widget)): return # We only have work to do, if there are JS Handlers in the form. if not hasattr(widget.form, 'jshandlers'): return # Only handle this event if we haven't already done so. if getattr(widget, '__z3c_formjs_subscriptions_created__', None) is True: return widget.__z3c_formjs_subscriptions_created__ = True # Step 1: Get the handler. handlers = widget.form.jshandlers.getHandlers(widget.field) # Step 2: Create a selector. selector = WidgetSelector(widget) # Step 3: Make sure that the form has JS subscriptions, otherwise add # it. if not interfaces.IHaveJSSubscriptions.providedBy(widget.form): widget.form.jsSubscriptions = jsevent.JSSubscriptions() zope.interface.alsoProvides( widget.form, interfaces.IHaveJSSubscriptions) # Step 4: Add the subscription to the form: for event, handler in handlers: widget.form.jsSubscriptions.subscribe(event, selector, handler)
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jsaction.py
jsaction.py
__docformat__ = "reStructuredText" import sys import cjson import zope.component import zope.interface from zope.publisher.interfaces import NotFound from zope.publisher.browser import BrowserPage from zope.traversing.api import getParents from z3c.traverser import traverser from z3c.form.util import SelectionManager, createCSSId from z3c.traverser.interfaces import ITraverserPlugin from z3c.formjs import interfaces def getUniquePrefixer(n=2, prefix='form'): def createPrefix(form): parents = getParents(form) return prefix + ''.join( [createCSSId(getattr(obj, '__name__', None) or obj.__class__.__name__) for obj in parents[:n]]) return createPrefix class AJAXHandlers(SelectionManager): """A selection manager for handling AJAX request handlers.""" zope.interface.implements(interfaces.IAJAXHandlers) managerInterface = interfaces.IAJAXHandlers def __init__(self, *args): handlers = [] for arg in args: if self.managerInterface.providedBy(arg): handlers += arg.items() elif interfaces.IAJAXHandler.providedBy(arg): handlers.append((arg.func.__name__, arg)) else: raise TypeError("Unrecognized argument type", arg) keys = [] seq = [] byname = {} for name, handler in handlers: keys.append(name) seq.append(handler) byname[name] = handler self._data_keys = keys self._data_values = seq self._data = byname def addHandler(self, name, handler): self._data_keys.append(name) self._data_values.append(handler) self._data[name] = handler def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.keys()) class AJAXHandler(object): zope.interface.implements(interfaces.IAJAXHandler) def __init__(self, func): self.func = func def __call__(self, view): result = self.func(view) if type(result) in (dict, list, set): try: result = cjson.encode(result) except TypeError: result = str(result) return result def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.func.__name__) class AJAXRequestHandler(object): """Mix-in class for forms to support AJAX calls.""" zope.interface.implements(interfaces.IAJAXRequestHandler, interfaces.IFormTraverser) ajaxRequestHandlers = AJAXHandlers() def handler(func): """A decorator for defining an AJAX request handler.""" handler = AJAXHandler(func) frame = sys._getframe(1) f_locals = frame.f_locals handlers = f_locals.setdefault('ajaxRequestHandlers', AJAXHandlers()) handlers.addHandler(func.__name__, handler) return handler class AJAXView(BrowserPage): """A wrapper class around AJAX handler to allow it to be publishable.""" def __init__(self, handler, request, view): self.context = self.handler = handler self.request = request self.__parent__ = self.view = view def __call__(self): return self.handler(self.view) class AJAXRequestTraverserPlugin(object): """Allow access to methods registered as an ajax request handler.""" zope.interface.implements(ITraverserPlugin) def __init__(self, context, request): self.context = context self.request = request def publishTraverse(self, request, name): handler = self.context.ajaxRequestHandlers.get(name) if handler is None: raise NotFound(self.context, name, request) return AJAXView(handler, self.request, self.context)
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/ajax.py
ajax.py
__docformat__ = "reStructuredText" import sys import zope.component import zope.interface from zope.interface import adapter from zope.security.management import getInteraction from zope.publisher.interfaces.browser import IBrowserRequest from z3c.formjs import interfaces, jsfunction CLIENT_EVENT_REQUEST_KEY = "z3c.formjs.jsclientevent.caughtEvents" class ClientEventHandlers(object): """Client Handlers for server side events.""" zope.interface.implements(interfaces.IClientEventHandlers) def __init__(self): self._registry = adapter.AdapterRegistry() self._handlers = () def addHandler(self, required, handler): """See interfaces.IClientEventHandlers""" # Register the handler self._registry.subscribe( required, interfaces.IClientEventHandler, handler) self._handlers += ((required, handler),) def getHandlers(self, event): """See interfaces.IClientEventHandlers""" return self._registry.subscriptions( map(zope.interface.providedBy, (event.object, event)), interfaces.IClientEventHandler) def copy(self): """See interfaces.IClientEventHandlers""" handlers = ClientEventHandlers() for eventSpec, handler in self._handlers: handlers.addHandler(eventSpec, handler) return handlers def __add__(self, other): """See interfaces.IClientEventHandlers""" if not isinstance(other, ClientEventHandlers): raise NotImplementedError handlers = self.copy() for required, handler in other._handlers: handlers.addHandler(required, handler) return handlers def __repr__(self): return '<ClientEventHandlers %r>' % [ handler for required, handler in self._handlers] class ClientEventHandler(object): zope.interface.implements(interfaces.IClientEventHandler) def __init__(self, required, func): self.required = required self.func = func def __call__(self, form, event): return self.func(form, event) def __repr__(self): return '<%s for %r>' % (self.__class__.__name__, self.required) def listener(required): """A decorator for defining a javascript function that is a listener.""" def createListener(func): frame = sys._getframe(1) f_locals = frame.f_locals handlers = f_locals.setdefault( 'jsClientListeners', ClientEventHandlers()) jsListener = ClientEventHandler(required, func) return handlers.addHandler(required, jsListener) return createListener @zope.component.adapter(zope.component.interfaces.IObjectEvent) def serverToClientEventLoader(event): """Event handler that listens for server side events and stores the event in the request to be picked up by the form and rendered as a client side function call.""" # Step 1: Get the interaction. try: interaction = getInteraction() except zope.security.interfaces.NoInteraction: # If there is no interaction, we simply return, because we cannot do # any work anyways. This also means that the event was not created # during a request, so we do not have a form anyways. return participations = interaction.participations # Step 2-1: Look for a request in the participation. request = None for part in participations: if IBrowserRequest.providedBy(part): request = part break # Step 2-2: If no request was found, we have nothing to do. if request is None: return # Step 3: Add the event to the list of events this handler has caught. events = request.annotations.setdefault(CLIENT_EVENT_REQUEST_KEY, []) if event not in events: events.append(event) class ClientEventsForm(object): """Mixin class to support calling of client side events.""" jsClientListeners = ClientEventHandlers() @property def eventCalls(self): events = self.request.annotations.get(CLIENT_EVENT_REQUEST_KEY, []) result = [] for event in events: if self.jsClientListeners.getHandlers(event): result.append(event) return result @property def eventInjections(self): results = [] for event in self.eventCalls: results += [h(self, event) for h in self.jsClientListeners.getHandlers(event)] results = '\n'.join(results) return results
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jsclientevent.py
jsclientevent.py
__docformat__ = "reStructuredText" import sys import zope.component import zope.interface from zope.publisher.interfaces.browser import IBrowserRequest from zope.viewlet import viewlet from z3c.formjs import interfaces class JSEvent(object): """Javascript Event""" zope.interface.implements(interfaces.IJSEvent) def __init__(self, name): self.name = name def __repr__(self): return '<JSEvent "%s">' % self.name CLICK = JSEvent("click") DBLCLICK = JSEvent("dblclick") CHANGE = JSEvent("change") LOAD = JSEvent("load") BLUR = JSEvent("blur") FOCUS = JSEvent("focus") KEYDOWN = JSEvent("keydown") KEYUP = JSEvent("keyup") MOUSEDOWN = JSEvent("mousedown") MOUSEMOVE = JSEvent("mousemove") MOUSEOUT = JSEvent("mouseout") MOUSEOVER = JSEvent("mouseover") MOUSEUP = JSEvent("mouseup") RESIZE = JSEvent("resize") SELECT = JSEvent("select") SUBMIT = JSEvent("submit") EVENTS = (CLICK, DBLCLICK, CHANGE, LOAD, BLUR, FOCUS, KEYDOWN, KEYUP, MOUSEDOWN, MOUSEMOVE, MOUSEOUT, MOUSEOVER, MOUSEUP, RESIZE, SELECT, SUBMIT) class IdSelector(object): zope.interface.implements(interfaces.IIdSelector) def __init__(self, id): self.id = id def __repr__(self): return '<%s "%s">' %(self.__class__.__name__, self.id) class CSSSelector(object): zope.interface.implements(interfaces.ICSSSelector) def __init__(self, expr): self.expr = expr def __repr__(self): return '<%s "%s">' %(self.__class__.__name__, self.expr) class JSSubscription(object): zope.interface.implements(interfaces.IJSSubscription) def __init__(self, event, selector, handler): self.event = event self.selector = selector self.handler = handler def __repr__(self): return '<%s event=%r, selector=%r, handler=%r>' % ( self.__class__.__name__, self.event, self.selector, self.handler) class JSSubscriptions(object): zope.interface.implements(interfaces.IJSSubscriptions) def __init__(self): self._subscriptions = {} def subscribe(self, event, selector, handler): subscription = JSSubscription(event, selector, handler) name = handler.__name__ subscriptions = self._subscriptions.get(name, []) subscriptions.append(subscription) self._subscriptions[name] = subscriptions return subscription def __iter__(self): for subscriptions in self._subscriptions.values(): for subscription in subscriptions: yield subscription def __getitem__(self, name): return self._subscriptions[name] def subscribe(selector, event=CLICK): """A decorator for defining a javascript event handler.""" def createSubscription(func): frame = sys._getframe(1) f_locals = frame.f_locals subs = f_locals.setdefault('jsSubscriptions', JSSubscriptions()) subs.subscribe(event, selector, func) func.__dict__['selector'] = selector func.__dict__['event'] = event return func return createSubscription class JSSubscriptionsViewlet(viewlet.ViewletBase): """An viewlet for the JS viewlet manager rendering subscriptions.""" zope.component.adapts( zope.interface.Interface, IBrowserRequest, interfaces.IHaveJSSubscriptions, zope.interface.Interface) # This viewlet wants to be very heavy, so that it is rendered after all # the JS libraries are loaded. weight = 1000 def update(self): self.renderer = zope.component.getMultiAdapter( (self.__parent__.jsSubscriptions, self.request), interfaces.IRenderer) self.renderer.update() def render(self): content = self.renderer.render() return u'<script type="text/javascript">\n%s\n</script>' % content
z3c.formjs
/z3c.formjs-0.5.0.tar.gz/z3c.formjs-0.5.0/src/z3c/formjs/jsevent.py
jsevent.py
__docformat__="restructuredtext" import os.path import zope.interface from zope.viewlet.viewlet import CSSViewlet from z3c.form import form, button, field from z3c.formui import layout from z3c.formjs import jsaction, jsevent, jsfunction, interfaces CalculatorCSSViewlet = CSSViewlet('calculator.css') class IGridButton(interfaces.IJSButton): """A button within the grid.""" class CalculatorButton(jsaction.JSButton): zope.interface.implements(IGridButton) def __init__(self, *args, **kwargs): kwargs['accessKey'] = kwargs['title'] super(CalculatorButton, self).__init__(*args, **kwargs) class Literal(CalculatorButton): """Marker class for Literals.""" pass class Operator(CalculatorButton): """Marker class for operators.""" pass class IButtons(zope.interface.Interface): one = Literal(title=u'1') two = Literal(title=u'2') three = Literal(title=u'3') add = Operator(title=u'+') four = Literal(title=u'4') five = Literal(title=u'5') six = Literal(title=u'6') subtract = Operator(title=u'-') seven = Literal(title=u'7') eight = Literal(title=u'8') nine = Literal(title=u'9') multiply = Operator(title=u'*') zero = Literal(title=u'0') decimal = Literal(title=u'.') equal = Operator(title=u'=') divide = Operator(title=u'/') clear = jsaction.JSButton(title=u"C") class GridButtonActions(button.ButtonActions): cols = 4 def grid(self): rows = [] current = [] for button in self.values(): if not IGridButton.providedBy(button.field): continue current.append(button) if len(current) == self.cols: rows.append(current) current = [] if current: current += [None]*(self.cols-len(current)) rows.append(current) return rows class CalculatorForm(layout.FormLayoutSupport, form.Form): zope.interface.implements(interfaces.IHaveJSFunctions) buttons = button.Buttons(IButtons) def updateActions(self): self.actions = GridButtonActions(self, self.request, self.context) self.actions.update() @jsfunction.function('calculator') def operate(self, id): return '''var operator = $("#operator .value").html(); var newOperator = $("#"+id).val(); var current = $("#current .value").html(); var stack = $("#stack .value").html(); if (operator == ""){ stack = current; operator = newOperator; } else if(newOperator == "="){ current = eval(stack+operator+current); stack = ""; operator = ""; } else { current = eval(stack+operator+current); stack = current; } $("#operator .value").html(operator); $("#stack .value").html(stack); $("#recentOperator .value").html("True"); $("#current .value").html(current);''' @jsfunction.function('calculator') def addLiteral(self, id): return '''var recentOperator = $("#recentOperator .value").html(); var current = $("#current .value").html(); var number = $("#" + id).val(); if (recentOperator != ""){ current = ""; } current = current+number; $("#current .value").html(current); $("#recentOperator .value").html(""); ''' @jsfunction.function('calculator') def clear(self): return '''$("#stack .value").html(""); $("#current .value").html(""); $("#operator .value").html(""); $("#recentOperator .value").html("");''' @jsaction.handler(Operator) def handleOperator(self, event, selector): return 'calculator.operate("%s")' % selector.widget.id @jsaction.handler(Literal) def handleLiteral(self, event, selector): return 'calculator.addLiteral("%s")' % selector.widget.id @jsaction.handler(buttons['clear']) def handlerClear(self, event, selector): return 'calculator.clear()'
z3c.formjsdemo
/z3c.formjsdemo-0.3.1.tar.gz/z3c.formjsdemo-0.3.1/src/z3c/formjsdemo/calculator/browser.py
browser.py
from zope.interface import Interface, implements from zope.security.proxy import removeSecurityProxy from zope.app.container.interfaces import INameChooser from zope.traversing.browser.absoluteurl import absoluteURL from zope.viewlet.viewlet import CSSViewlet from zope.component import getMultiAdapter from zope.viewlet.viewlet import JavaScriptViewlet from zope.publisher.interfaces.browser import IBrowserPage from zope.component import getMultiAdapter from zope.publisher.interfaces import IPublishTraverse from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.component.interfaces import IObjectEvent from zope.app.container.interfaces import IObjectAddedEvent from zope.session.interfaces import ISession from z3c.form import form, field, button from z3c.formui import layout from z3c.form.interfaces import IWidgets, DISPLAY_MODE from z3c.formjs import jsaction, jsfunction, jsclientevent, ajax from z3c.formjs.interfaces import IJSButton import tree, interfaces TreeCSSViewlet = CSSViewlet('tree.css') JQueryFormPluginViewlet = JavaScriptViewlet('jquery.form.js') SESSION_KEY = 'z3c.formjsdemo.tree' class PrefixForm(object): postfix = '' @property def prefix(self): url = absoluteURL(self.context, self.request) return '-'.join((str(hash(url)), str(self.postfix))) class EventsForm(jsclientevent.ClientEventsForm): @jsclientevent.listener((interfaces.ITreeNode, IObjectEvent)) def updateEventList(self, event): info = repr(event).replace('<','&lt;').replace('>','&gt;').replace('"',"'") return '$("#server-events-container").append("<div>%s</div>")' % info class TreeNodeInlineAddForm(PrefixForm, EventsForm, form.AddForm): """Form for adding a tree node. This page is meant to be inlined into another page. """ label = "Add a Tree Node" fields = field.Fields(interfaces.ITreeNode).select('title') postfix = 'add' jsClientListeners = EventsForm.jsClientListeners @jsclientevent.listener((interfaces.ITreeNode, IObjectAddedEvent)) def updateContents(self, event): indexForm = TreeNodeInlineForm(self.context, self.request) indexForm.update() expandId = indexForm.actions['expand'].id return '$("#%s").click()' % expandId def create(self, data): return tree.TreeNode(data['title']) def add(self, object): name = object.title.lower().replace(' ','') context = removeSecurityProxy(self.context) name = INameChooser(context).chooseName(name, object) context[name] = object self._name = name def render(self): """Custom render method that does not use nextURL method.""" if self._finishedAdd: return '<script type="text/javascript">%s</script>' % self.eventInjections return super(TreeNodeInlineAddForm, self).render() class TreeNodeAddForm(layout.FormLayoutSupport, TreeNodeInlineAddForm): """Stand Along version of the addform. This form is meant to appear on a page all by itself. """ def nextURL(self): return absoluteURL(removeSecurityProxy(self.context)[self._name], self.request) # this will use the nextURL method render = form.AddForm.render class TreeNodeForm(PrefixForm, layout.FormLayoutSupport, form.Form): postfix = 'main' # distinguish prefix from others on the page. fields = field.Fields(interfaces.ITreeNode).select('title') def updateWidgets(self): self.widgets = getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.mode = DISPLAY_MODE self.widgets.update() @jsfunction.function('tree') def expandNode(self, url, expanderId, contractorId, containerId): """Expand the node that using the given prefix and url""" return ''' $.get(url, function(data){ $("#"+expanderId).addClass("hidden"); $("#"+contractorId).removeClass("hidden"); $("#"+containerId).html(data); } ); ''' @jsfunction.function('tree') def contractNode(self, expanderId, contractorId, containerId): """Expand the node that using the given prefix and url""" return ''' $("#"+expanderId).removeClass("hidden"); $("#"+contractorId).addClass("hidden"); $("#"+containerId).html(''); ''' class IButtons(Interface): """Buttons for the inline tree node form.""" expand = jsaction.JSButton(title=u'+') contract = jsaction.JSButton(title=u'-') class TreeNodeInlineForm(PrefixForm, ajax.AJAXRequestHandler, EventsForm, form.Form): fields = field.Fields(interfaces.ITreeNode).select('title') buttons = button.Buttons(IButtons) jsClientListeners = EventsForm.jsClientListeners @jsaction.handler(buttons['expand']) def handleExpand(self, event, selector): url = absoluteURL(self.context, self.request) + '/@@contents' call = TreeNodeForm.expandNode.call(url, self.actions['expand'].id, self.actions['contract'].id, self.prefix+'-inlinecontent') path = absoluteURL(self.context, self.request) store = '$.get("%s/@@inline/@@ajax/storeExpand", function(data){});' % path return '\n'.join((call, store)) @jsaction.handler(buttons['contract']) def handleContract(self, event, selector): call = TreeNodeForm.contractNode.call(self.actions['expand'].id, self.actions['contract'].id, self.prefix+'-inlinecontent') path = absoluteURL(self.context, self.request) store = '$.get("%s/@@inline/@@ajax/storeContract", function(data){});' % path return '\n'.join((call, store)) @ajax.handler def storeExpand(self): self._setExpanded(True) return "success" @ajax.handler def storeContract(self): self._setExpanded(False) return "success" def _setExpanded(self, value): session = ISession(self.request)[SESSION_KEY] session[self.prefix + '-expanded'] = value @property def expanded(self): session = ISession(self.request)[SESSION_KEY] return session.get(self.prefix+'-expanded', False) def updateActions(self): super(TreeNodeInlineForm, self).updateActions() if self.expanded: self.actions['expand'].addClass('hidden') else: self.actions['contract'].addClass('hidden') def updateWidgets(self): self.widgets = getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.mode = DISPLAY_MODE self.widgets.update() class TreeNodeInlineEditForm(PrefixForm, EventsForm, form.EditForm): fields = field.Fields(interfaces.ITreeNode).select('title') jsClientListeners = EventsForm.jsClientListeners _applyChangesWasCalled = False def applyChanges(self, data): self._applyChangesWasCalled = True return super(TreeNodeInlineEditForm, self).applyChanges(data) @jsclientevent.listener((interfaces.ITreeNode, IObjectModifiedEvent)) def updateTitle(self, event): inlineform = TreeNodeInlineForm(self.context, self.request) inlineform.update() titleId = inlineform.widgets['title'].id mainform = TreeNodeForm(self.context, self.request) mainform.update() mainTitleId = mainform.widgets['title'].id lines = ['$("#%s").html("%s")' % (titleId, self.context.title), '$("#%s").html("%s")' % (mainTitleId, self.context.title)] return '\n'.join(lines) def render(self): if self._applyChangesWasCalled: return '<script type="text/javascript">%s</script>' % self.eventInjections else: return super(TreeNodeInlineEditForm, self).render() class IInlineFormButton(IJSButton): """A button that points to an inline form.""" class InlineFormButton(jsaction.JSButton): """implementer of IInlineFormButton""" implements(IInlineFormButton) class IContentButtons(Interface): """Buttons for the inline contents view.""" add = InlineFormButton(title=u'Add') edit = InlineFormButton(title=u'Edit') class TreeNodeInlineContentsForm(PrefixForm, form.Form): postfix = 'contents' buttons = button.Buttons(IContentButtons) def _handleInlineFormButton(self, viewURL): return '''$.get("%s", function(data){ $("#%s-inlineform").html(data); $("#%s-inlineform form").ajaxForm( function(data){ $("body").append(data); }); }); ''' % (viewURL, self.prefix, self.prefix) @jsaction.handler(buttons['add']) def handleAdd(self, event, selector): viewURL = absoluteURL(self.context, self.request) + '/@@add' return self._handleInlineFormButton(viewURL) @jsaction.handler(buttons['edit']) def handleEdit(self, event, selector): viewURL = absoluteURL(self.context, self.request) + '/@@edit' return self._handleInlineFormButton(viewURL)
z3c.formjsdemo
/z3c.formjsdemo-0.3.1.tar.gz/z3c.formjsdemo-0.3.1/src/z3c/formjsdemo/tree/browser.py
browser.py
* ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX. * * ajaxSubmit accepts a single argument which can be either a success callback function * or an options Object. If a function is provided it will be invoked upon successful * completion of the submit and will be passed the response from the server. * If an options Object is provided, the following attributes are supported: * * target: Identifies the element(s) in the page to be updated with the server response. * This value may be specified as a jQuery selection string, a jQuery object, * or a DOM element. * default value: null * * url: URL to which the form data will be submitted. * default value: value of form's 'action' attribute * * type: The method in which the form data should be submitted, 'GET' or 'POST'. * default value: value of form's 'method' attribute (or 'GET' if none found) * * beforeSubmit: Callback method to be invoked before the form is submitted. * default value: null * * success: Callback method to be invoked after the form has been successfully submitted * and the response has been returned from the server * default value: null * * dataType: Expected dataType of the response. One of: null, 'xml', 'script', or 'json' * default value: null * * semantic: Boolean flag indicating whether data must be submitted in semantic order (slower). * default value: false * * resetForm: Boolean flag indicating whether the form should be reset if the submit is successful * * clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful * * * The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for * validating the form data. If the 'beforeSubmit' callback returns false then the form will * not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data * in array format, the jQuery object, and the options object passed into ajaxSubmit. * The form data array takes the following form: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * If a 'success' callback method is provided it is invoked after the response has been returned * from the server. It is passed the responseText or responseXML value (depending on dataType). * See jQuery.ajax for further details. * * * The dataType option provides a means for specifying how the server response should be handled. * This maps directly to the jQuery.httpData method. The following values are supported: * * 'xml': if dataType == 'xml' the server response is treated as XML and the 'after' * callback method, if specified, will be passed the responseXML value * 'json': if dataType == 'json' the server response will be evaluted and passed to * the 'after' callback, if specified * 'script': if dataType == 'script' the server response is evaluated in the global context * * * Note that it does not make sense to use both the 'target' and 'dataType' options. If both * are provided the target will be ignored. * * The semantic argument can be used to force form serialization in semantic order. * This is normally true anyway, unless the form contains input elements of type='image'. * If your form must be submitted with name/value pairs in semantic order and your form * contains an input of type='image" then pass true for this arg, otherwise pass false * (or nothing) to avoid the overhead for this logic. * * * When used on its own, ajaxSubmit() is typically bound to a form's submit event like this: * * $("#form-id").submit(function() { * $(this).ajaxSubmit(options); * return false; // cancel conventional submit * }); * * When using ajaxForm(), however, this is done for you. * * @example * $('#myForm').ajaxSubmit(function(data) { * alert('Form submit succeeded! Server returned: ' + data); * }); * @desc Submit form and alert server response * * * @example * var options = { * target: '#myTargetDiv' * }; * $('#myForm').ajaxSubmit(options); * @desc Submit form and update page element with server response * * * @example * var options = { * success: function(responseText) { * alert(responseText); * } * }; * $('#myForm').ajaxSubmit(options); * @desc Submit form and alert the server response * * * @example * var options = { * beforeSubmit: function(formArray, jqForm) { * if (formArray.length == 0) { * alert('Please enter data.'); * return false; * } * } * }; * $('#myForm').ajaxSubmit(options); * @desc Pre-submit validation which aborts the submit operation if form data is empty * * * @example * var options = { * url: myJsonUrl.php, * dataType: 'json', * success: function(data) { * // 'data' is an object representing the the evaluated json data * } * }; * $('#myForm').ajaxSubmit(options); * @desc json data returned and evaluated * * * @example * var options = { * url: myXmlUrl.php, * dataType: 'xml', * success: function(responseXML) { * // responseXML is XML document object * var data = $('myElement', responseXML).text(); * } * }; * $('#myForm').ajaxSubmit(options); * @desc XML data returned from server * * * @example * var options = { * resetForm: true * }; * $('#myForm').ajaxSubmit(options); * @desc submit form and reset it if successful * * @example * $('#myForm).submit(function() { * $(this).ajaxSubmit(); * return false; * }); * @desc Bind form's submit event to use ajaxSubmit * * * @name ajaxSubmit * @type jQuery * @param options object literal containing options which control the form submission process * @cat Plugins/Form * @return jQuery * @see formToArray * @see ajaxForm * @see $.ajax * @author jQuery Community */ jQuery.fn.ajaxSubmit = function(options) { if (typeof options == 'function') options = { success: options }; options = jQuery.extend({ url: this.attr('action') || window.location, type: this.attr('method') || 'GET' }, options || {}); var a = this.formToArray(options.semantic); // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this; // fire vetoable 'validate' event var veto = {}; jQuery.event.trigger('form.submit.validate', [a, this, options, veto]); if (veto.veto) return this; var q = jQuery.param(a);//.replace(/%20/g,'+'); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else options.data = q; // data is the query string for 'post' var $form = this, callbacks = []; if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data, status) { jQuery(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, [data, status]); }); } else if (options.success) callbacks.push(options.success); options.success = function(data, status) { for (var i=0, max=callbacks.length; i < max; i++) callbacks[i](data, status); }; // are there files to upload? var files = jQuery('input:file', this).fieldValue(); var found = false; for (var j=0; j < files.length; j++) if (files[j]) found = true; if (options.iframe || found) // options.iframe allows user to force iframe mode fileUpload(); else jQuery.ajax(options); // fire 'notify' event jQuery.event.trigger('form.submit.notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; var opts = jQuery.extend({}, jQuery.ajaxSettings, options); var id = 'jqFormIO' + jQuery.fn.ajaxSubmit.counter++; var $io = jQuery('<iframe id="' + id + '" name="' + id + '" />'); var io = $io[0]; var op8 = jQuery.browser.opera && window.opera.version() < 9; if (jQuery.browser.msie || op8) io.src = 'javascript:false;document.write("");'; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); // make sure form attrs are set form.method = 'POST'; form.encoding ? form.encoding = 'multipart/form-data' : form.enctype = 'multipart/form-data'; var xhr = { // mock object responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {} }; var g = opts.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! jQuery.active++) jQuery.event.trigger("ajaxStart"); if (g) jQuery.event.trigger("ajaxSend", [xhr, opts]); var cbInvoked = 0; var timedOut = 0; // take a breath so that pending repaints get some cpu time before the upload starts setTimeout(function() { $io.appendTo('body'); // jQuery's event binding doesn't work for iframe events in IE io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.action = opts.url; var t = form.target; form.target = id; // support timout if (opts.timeout) setTimeout(function() { timedOut = true; cb(); }, opts.timeout); form.submit(); form.target = t; // reset }, 10); function cb() { if (cbInvoked++) return; io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) throw 'timeout'; // extract the server response from the iframe var data, doc; doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; xhr.responseText = doc.body ? doc.body.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (opts.dataType == 'json' || opts.dataType == 'script') { var ta = doc.getElementsByTagName('textarea')[0]; data = ta ? ta.value : xhr.responseText; if (opts.dataType == 'json') eval("data = " + data); else jQuery.globalEval(data); } else if (opts.dataType == 'xml') { data = xhr.responseXML; if (!data && xhr.responseText != null) data = toXml(xhr.responseText); } else { data = xhr.responseText; } } catch(e){ ok = false; jQuery.handleError(opts, xhr, 'error', e); } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { opts.success(data, 'success'); if (g) jQuery.event.trigger("ajaxSuccess", [xhr, opts]); } if (g) jQuery.event.trigger("ajaxComplete", [xhr, opts]); if (g && ! --jQuery.active) jQuery.event.trigger("ajaxStop"); if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error'); // clean up setTimeout(function() { $io.remove(); xhr.responseXML = null; }, 100); }; function toXml(s, doc) { if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else doc = (new DOMParser()).parseFromString(s, 'text/xml'); return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null; } }; }; jQuery.fn.ajaxSubmit.counter = 0; // used to create unique iframe ids /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * Note that for accurate x/y coordinates of image submit elements in all browsers * you need to also use the "dimensions" plugin (this method will auto-detect its presence). * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. See ajaxSubmit for a full description of the options argument. * * * @example * var options = { * target: '#myTargetDiv' * }; * $('#myForm').ajaxSForm(options); * @desc Bind form's submit event so that 'myTargetDiv' is updated with the server response * when the form is submitted. * * * @example * var options = { * success: function(responseText) { * alert(responseText); * } * }; * $('#myForm').ajaxSubmit(options); * @desc Bind form's submit event so that server response is alerted after the form is submitted. * * * @example * var options = { * beforeSubmit: function(formArray, jqForm) { * if (formArray.length == 0) { * alert('Please enter data.'); * return false; * } * } * }; * $('#myForm').ajaxSubmit(options); * @desc Bind form's submit event so that pre-submit callback is invoked before the form * is submitted. * * * @name ajaxForm * @param options object literal containing options which control the form submission process * @return jQuery * @cat Plugins/Form * @type jQuery * @see ajaxSubmit * @author jQuery Community */ jQuery.fn.ajaxForm = function(options) { return this.each(function() { jQuery("input:submit,input:image,button:submit", this).click(function(ev) { var $form = this.form; $form.clk = this; if (this.type == 'image') { if (ev.offsetX != undefined) { $form.clk_x = ev.offsetX; $form.clk_y = ev.offsetY; } else if (typeof jQuery.fn.offset == 'function') { // try to use dimensions plugin var offset = jQuery(this).offset(); $form.clk_x = ev.pageX - offset.left; $form.clk_y = ev.pageY - offset.top; } else { $form.clk_x = ev.pageX - this.offsetLeft; $form.clk_y = ev.pageY - this.offsetTop; } } // clear form vars setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10); }) }).submit(function(e) { jQuery(this).ajaxSubmit(options); return false; }); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. * * The semantic argument can be used to force form serialization in semantic order. * This is normally true anyway, unless the form contains input elements of type='image'. * If your form must be submitted with name/value pairs in semantic order and your form * contains an input of type='image" then pass true for this arg, otherwise pass false * (or nothing) to avoid the overhead for this logic. * * @example var data = $("#myForm").formToArray(); * $.post( "myscript.cgi", data ); * @desc Collect all the data from a form and submit it to the server. * * @name formToArray * @param semantic true if serialization must maintain strict semantic ordering of elements (slower) * @type Array<Object> * @cat Plugins/Form * @see ajaxForm * @see ajaxSubmit * @author jQuery Community */ jQuery.fn.formToArray = function(semantic) { var a = []; if (this.length == 0) return a; var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) return a; for(var i=0, max=els.length; i < max; i++) { var el = els[i]; var n = el.name; if (!n) continue; if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); continue; } var v = jQuery.fieldValue(el, true); if (v === null) continue; if (v.constructor == Array) { for(var j=0, jmax=v.length; j < jmax; j++) a.push({name: n, value: v[j]}); } else a.push({name: n, value: v}); } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle them here var inputs = form.getElementsByTagName("input"); for(var i=0, max=inputs.length; i < max; i++) { var input = inputs[i]; var n = input.name; if(n && !input.disabled && input.type == "image" && form.clk == input) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 * * The semantic argument can be used to force form serialization in semantic order. * If your form must be submitted with name/value pairs in semantic order then pass * true for this arg, otherwise pass false (or nothing) to avoid the overhead for * this logic (which can be significant for very large forms). * * @example var data = $("#myForm").formSerialize(); * $.ajax('POST', "myscript.cgi", data); * @desc Collect all the data from a form into a single string * * @name formSerialize * @param semantic true if serialization must maintain strict semantic ordering of elements (slower) * @type String * @cat Plugins/Form * @see formToArray * @author jQuery Community */ jQuery.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return jQuery.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 * * The successful argument controls whether or not serialization is limited to * 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. * * @example var data = $("input").formSerialize(); * @desc Collect the data from all successful input elements into a query string * * @example var data = $(":radio").formSerialize(); * @desc Collect the data from all successful radio input elements into a query string * * @example var data = $("#myForm :checkbox").formSerialize(); * @desc Collect the data from all successful checkbox input elements in myForm into a query string * * @example var data = $("#myForm :checkbox").formSerialize(false); * @desc Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string * * @example var data = $(":input").formSerialize(); * @desc Collect the data from all successful input, select, textarea and button elements into a query string * * @name fieldSerialize * @param successful true if only successful controls should be serialized (default is true) * @type String * @cat Plugins/Form */ jQuery.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) return; var v = jQuery.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) a.push({name: n, value: v[i]}); } else if (v !== null && typeof v != 'undefined') a.push({name: this.name, value: v}); }); //hand off to jQuery.param for proper encoding return jQuery.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. * * @example var data = $("#myPasswordElement").fieldValue(); * alert(data[0]); * @desc Alerts the current value of the myPasswordElement element * * @example var data = $("#myForm :input").fieldValue(); * @desc Get the value(s) of the form elements in myForm * * @example var data = $("#myForm :checkbox").fieldValue(); * @desc Get the value(s) for the successful checkbox element(s) in the jQuery object. * * @example var data = $("#mySingleSelect").fieldValue(); * @desc Get the value(s) of the select control * * @example var data = $(':text').fieldValue(); * @desc Get the value(s) of the text input or textarea elements * * @example var data = $("#myMultiSelect").fieldValue(); * @desc Get the values for the select-multiple control * * @name fieldValue * @param Boolean successful true if only the values for successful controls should be returned (default is true) * @type Array<String> * @cat Plugins/Form */ jQuery.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = jQuery.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) continue; v.constructor == Array ? jQuery.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If the given element is not * successful and the successful arg is not false then the returned value will be null. * * Note: If the successful flag is true (default) but the element is not successful, the return will be null * Note: The value returned for a successful select-multiple element will always be an array. * Note: If the element has no value the return value will be undefined. * * @example var data = jQuery.fieldValue($("#myPasswordElement")[0]); * @desc Gets the current value of the myPasswordElement element * * @name fieldValue * @param Element el The DOM element for which the value will be returned * @param Boolean successful true if value returned must be for a successful controls (default is true) * @type String or Array<String> or null or undefined * @cat Plugins/Form */ jQuery.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (typeof successful == 'undefined') successful = true; if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) return null; if (tag == 'select') { var index = el.selectedIndex; if (index < 0) return null; var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { // extra pain for IE... var v = jQuery.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value; if (one) return v; a.push(v); } } return a; } return el.value; }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected * * @example $('form').clearForm(); * @desc Clears all forms on the page. * * @name clearForm * @type jQuery * @cat Plugins/Form * @see resetForm */ jQuery.fn.clearForm = function() { return this.each(function() { jQuery('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. Takes the following actions on the matched elements: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected * * @example $('.myInputs').clearFields(); * @desc Clears all inputs with class myInputs * * @name clearFields * @type jQuery * @cat Plugins/Form * @see clearForm */ jQuery.fn.clearFields = jQuery.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') this.value = ''; else if (t == 'checkbox' || t == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. * * @example $('form').resetForm(); * @desc Resets all forms on the page. * * @name resetForm * @type jQuery * @cat Plugins/Form * @see clearForm */ jQuery.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) this.reset(); }); };
z3c.formjsdemo
/z3c.formjsdemo-0.3.1.tar.gz/z3c.formjsdemo-0.3.1/src/z3c/formjsdemo/tree/jquery.form.js
jquery.form.js
__docformat__="restructuredtext" import os.path import zope.interface from zope.viewlet.viewlet import CSSViewlet, JavaScriptViewlet from zope.app.container.interfaces import INameChooser from zope.traversing.browser import absoluteURL from zope.security.proxy import removeSecurityProxy from zope.session.interfaces import ISession from z3c.form import form, button, field from z3c.form.interfaces import IWidgets from z3c.formui import layout from z3c.formjs import jsaction, jsevent, ajax from z3c.formjsdemo.chat import chat, interfaces SESSION_KEY = 'z3c.formjsdemo.chat' ChatCSSViewlet = CSSViewlet('chat.css') ChatJSViewlet = JavaScriptViewlet('chat.js') class SessionProperty(object): def __init__(self, name, default=None): self.name = name self.default = default def __get__(self, inst, klass): session = ISession(inst.request)[SESSION_KEY] return session.get(self.name, self.default) def __set__(self, inst, value): session = ISession(inst.request)[SESSION_KEY] session[self.name] = value class ChatRoomAddForm(layout.FormLayoutSupport, form.AddForm): label = "Add a Chat Room" fields = field.Fields(interfaces.IChatRoom).select('topic') def create(self, data): return chat.ChatRoom(data['topic']) def add(self, object): name = object.topic.lower().replace(' ','') context = removeSecurityProxy(self.context) name = INameChooser(context).chooseName(name, object) context[name] = object self._name = name def nextURL(self): return absoluteURL(removeSecurityProxy(self.context)[self._name], self.request) class IButtons(zope.interface.Interface): send = jsaction.JSButton(title=u'Send') connect = jsaction.JSButton(title=u'Connect') class IFields(zope.interface.Interface): message = zope.schema.TextLine(title=u"Message") nick = zope.schema.TextLine(title=u"Nick") class ChatForm(layout.FormLayoutSupport, ajax.AJAXRequestHandler, form.Form): buttons = button.Buttons(IButtons) fields = field.Fields(IFields) nick = SessionProperty('nick') @jsaction.handler(buttons['connect']) def handleConnect(self, event, selecter): nickId = self.widgets['nick'].id messageId = self.widgets['message'].id return '''$.get("@@index.html/@@ajax/joinChat", {nick: $("#%s").val()}, function(data){ $("#%s").attr("disabled", "true"); $("#connect").addClass("translucent"); $("#online").removeClass("translucent"); $("#%s").removeAttr("disabled"); }); ''' % (nickId, nickId, messageId) def _send(self, messageId): return '''$.get("@@index.html/@@ajax/addMessage", {message: $("#%s").val()}, function(data){ $("#%s").val(""); } );''' % (messageId, messageId) @jsaction.handler(fields['message'], event=jsevent.KEYDOWN) def handleMessageEnter(self, event, selecter): return '''if (event.which != 13){ return null; } %s''' % self._send(self.widgets['message'].id) @jsaction.handler(buttons['send']) def handleSend(self, event, selecter): return self._send(self.widgets['message'].id) def updateWidgets(self): '''See interfaces.IForm''' self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.ignoreContext = True self.widgets.update() @ajax.handler def getMessages(self): index = int(self.request.get('index')) result = "" for nick, message in self.context.messages[index:]: result += self._renderMessage(nick, message) return result @ajax.handler def addMessage(self): message = self.request.get('message') if message is not None: self.context.addMessage(self.nick, message) return self._renderMessage(self.nick, message) @ajax.handler def joinChat(self): self.nick = self.request.get('nick', 'anonymous') return "Connected as %s" % self.nick def _renderMessage(self, nick, message): return '<div class="message"><span class="nick">%s:</span>%s</div>' % ( nick, message)
z3c.formjsdemo
/z3c.formjsdemo-0.3.1.tar.gz/z3c.formjsdemo-0.3.1/src/z3c/formjsdemo/chat/browser.py
browser.py
==================== Form User Interfaces ==================== This package provides several useful templates to get a quick start with the ``z3c.form`` package. Previous form frameworks always included default templates that were implemented in a particular user-interface development pattern. If you wanted to use an alternative strategy to develop user interfaces, it was often tedious to do so. This package aims to provide some options without requiring them for the basic framework. Layout Template Support ----------------------- One common pattern in Zope 3 user interface development is the use of layout templates (see z3c.template). This package provides some mixin classes to the regular form classes to support layout-based templating. >>> from z3c.form import testing >>> testing.setupFormDefaults() Before we can start writing forms, we must have the content to work with: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... ... name = zope.schema.TextLine( ... title=u'Name', ... required=True) ... ... age = zope.schema.Int( ... title=u'Age', ... description=u"The person's age.", ... min=0, ... default=20, ... required=False) >>> from zope.schema.fieldproperty import FieldProperty >>> @zope.interface.implementer(IPerson) ... class Person(object): ... name = FieldProperty(IPerson['name']) ... age = FieldProperty(IPerson['age']) ... ... def __init__(self, name, age): ... self.name = name ... self.age = age ... ... def __repr__(self): ... return '<%s %r>' % (self.__class__.__name__, self.name) Okay, that should suffice for now. Let's now create a working add form: >>> from z3c.form import field >>> from z3c.formui import form, layout >>> class PersonAddForm(form.AddForm): ... ... fields = field.Fields(IPerson) ... ... def create(self, data): ... return Person(**data) ... ... def add(self, object): ... self.context[object.id] = object ... ... def nextURL(self): ... return 'index.html' Let's create a request: >>> from z3c.form.testing import TestRequest >>> from zope.interface import alsoProvides >>> divRequest = TestRequest() And support the div form layer for our request: >>> from z3c.formui.interfaces import IDivFormLayer >>> alsoProvides(divRequest, IDivFormLayer) Now create the form: >>> addForm = PersonAddForm(root, divRequest) Since we have not specified a template yet, we have to do this now. We use our div based form template: >>> import os >>> import z3c.formui >>> divFormTemplate = os.path.join(os.path.dirname(z3c.formui.__file__), ... 'div-form.pt') >>> from z3c.template.template import TemplateFactory >>> divFormFactory = TemplateFactory(divFormTemplate, 'text/html') Now register the form (content) template: >>> import zope.interface >>> import zope.component >>> from z3c.template.interfaces import IContentTemplate >>> zope.component.provideAdapter(divFormFactory, ... (zope.interface.Interface, IDivFormLayer), ... IContentTemplate) And let's define a layout template which simply calls the render method. For a more advanced content/layout render concept see z3c.pagelet. >>> import tempfile >>> temp_dir = tempfile.mkdtemp() >>> myLayout = os.path.join(temp_dir, 'myLayout.pt') >>> with open(myLayout, 'w') as file: ... _ = file.write('''<html> ... <body> ... <tal:block content="structure view/render"> ... content ... </tal:block> ... </body> ... </html>''') >>> myLayoutFactory = TemplateFactory(myLayout, 'text/html') >>> from z3c.template.interfaces import ILayoutTemplate >>> zope.component.provideAdapter(myLayoutFactory, ... (zope.interface.Interface, zope.interface.Interface), ILayoutTemplate) Now we can get our layout template: >>> layout = zope.component.getMultiAdapter((addForm, divRequest), ... ILayoutTemplate) >>> layout.__class__.__name__ 'ViewPageTemplateFile' >>> os.path.basename(layout.filename) 'myLayout.pt' DIV-based Layout ---------------- Let's now render the page. Note the output doesn't contain the layout template: >>> addForm.update() >>> print(addForm.render()) <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <div id="form-widgets-name-row" class="row required"> <div class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required">*</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> </div> <div id="form-widgets-age-row" class="row"> <div class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> </div> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> </form> But we can call our form which uses the new layout template which renders the form within the div-form content template: >>> print(addForm()) <html> <body> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <div id="form-widgets-name-row" class="row required"> <div class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required">*</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> </div> <div id="form-widgets-age-row" class="row"> <div class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> </div> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> </form> </body> </html> Table-based Forms ----------------- There is a table based layout too. Let's define the template and use them: >>> from z3c.formui.interfaces import ITableFormLayer >>> tableFormTemplate = os.path.join(os.path.dirname(z3c.formui.__file__), ... 'table-form.pt') >>> from z3c.template.template import TemplateFactory >>> tableFormFactory = TemplateFactory(tableFormTemplate, 'text/html') Now register the form (content) template: >>> zope.component.provideAdapter(tableFormFactory, ... (zope.interface.Interface, ITableFormLayer), IContentTemplate) Patch the request and call the form again: >>> tableRequest = TestRequest() >>> alsoProvides(tableRequest, ITableFormLayer) Now our new request should know the table based form template: >>> addForm = PersonAddForm(root, tableRequest) >>> print(addForm()) <html> <body> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <table class="form-fields"> <tr class="row required"> <td class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required"> * </span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> </td> </tr> <tr class="row"> <td class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> </td> </tr> </table> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> </form> </body> </html> `AddForm` rendering for `IAdding` --------------------------------- The `z3c.formui` package also provides a layout-aware version of `z3c.form.adding.AddForm` which can be used for creating forms for the `zope.app.container.interfaces.IAdding` mechanism. Let's check its template support. First, create the form for an `Adding` instance. We just need to define the ``create()`` method, because the default ``add()`` and ``nextURL()`` methods are already defined using the `Adding` object. >>> from z3c.formui import adding >>> class AddingPersonAddForm(adding.AddForm): ... ... fields = field.Fields(IPerson) ... ... def create(self, data): ... return Person(**data) Let's now instantiate the "fake" adding component and the add form: >>> class Adding(object): ... def __init__(self, context, request): ... self.context = context ... self.request = request >>> rootAdding = Adding(root, divRequest) >>> addForm = AddingPersonAddForm(rootAdding, divRequest) First, let's ensure that we can lookup a layout template for the form: >>> layout = zope.component.getMultiAdapter( ... (addForm, divRequest), ILayoutTemplate) >>> layout.__class__.__name__ 'ViewPageTemplateFile' Okay, that worked. Let's now render the div-based addform: >>> print(addForm()) <html> <body> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <div id="form-widgets-name-row" class="row required"> <div class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required">*</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> </div> <div id="form-widgets-age-row" class="row"> <div class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> </div> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> </form> </body> </html> Okay, now we are going to check table layout support. >>> rootAdding = Adding(root, tableRequest) >>> addForm = AddingPersonAddForm(rootAdding, tableRequest) Again, the layout should be available: >>> layout = zope.component.getMultiAdapter((addForm, tableRequest), ... ILayoutTemplate) >>> layout.__class__.__name__ 'ViewPageTemplateFile' Let's now render the form: >>> print(addForm()) <html> <body> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <table class="form-fields"> <tr class="row required"> <td class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required"> * </span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> </td> </tr> <tr class="row"> <td class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="20" /> </div> </td> </tr> </table> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </div> </form> </body> </html> Form Macros ----------- Load the configuration, which will make sure that all macros get registered correctly: >>> from zope.configuration import xmlconfig >>> import zope.component >>> import zope.viewlet >>> import zope.security >>> import zope.publisher >>> import zope.browserresource >>> import z3c.macro >>> import z3c.template >>> import z3c.formui >>> xmlconfig.XMLConfig('meta.zcml', zope.component)() >>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)() >>> xmlconfig.XMLConfig('meta.zcml', zope.security)() >>> xmlconfig.XMLConfig('meta.zcml', zope.publisher)() >>> xmlconfig.XMLConfig('meta.zcml', zope.browserresource)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.template)() >>> xmlconfig.XMLConfig('configure.zcml', z3c.formui)() Div IContentTemplate -------------------- Create some dummy form discriminators for calling div layout templates and macros and check the div IContentTemplates: >>> objects = (addForm, divRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate).filename '...div-form.pt' >>> objects = (form.DisplayForm(None, None), divRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, '').filename '...div-form-display.pt' We offer the following named IContentTemplate: >>> objects = (form.DisplayForm(None, None), divRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, ... 'display').filename '...div-form-display.pt' >>> objects = (form.DisplayForm(None, None), divRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, ... 'subform').filename '...subform.pt' Table ILayoutTemplate --------------------- There is one generic layout template to build sub forms: >>> objects = (form.DisplayForm(None, None), divRequest) >>> zope.component.getMultiAdapter(objects, ILayoutTemplate, ... 'subform').filename '...subform-layout.pt' Div layout macros ----------------- We have different form macros available for IInputForm: >>> from z3c.macro.interfaces import IMacroTemplate >>> objects = (None, addForm, divRequest) >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form') [...div-form.pt'), ...metal:define-macro': u'form'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'subform') [...div-form.pt'), ...define-macro': u'subform'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-label') [...div-form.pt'), ...define-macro': u'label'... >>> zope.component.getMultiAdapter( ... objects, IMacroTemplate, 'form-required-info') [...div-form.pt'), ...define-macro', u'required-info'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-header') [...div-form.pt'), ...define-macro': u'header'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-errors') [...div-form.pt'), ...define-macro': u'errors'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'widget-rows') [...div-form.pt'), ...define-macro': u'widget-rows'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'widget-row') [...div-form.pt'), ...define-macro': u'widget-row'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-groups') [...div-form.pt'), ...define-macro': u'groups'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-buttons') [...div-form.pt'), ...define-macro', u'buttons'... And we have different form macros available for IDisplayForm: >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'subform-display') [...div-form-display.pt'), ...define-macro': u'subform-display'... Table IContentTemplate ---------------------- Create some dummy form discriminators for calling table layout templates and macros and check the div IContentTemplates: >>> objects = (addForm, tableRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, '').filename '...table-form.pt' >>> objects = (form.DisplayForm(None, None), tableRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, '').filename '...table-form-display.pt' We offer the following named IContentTemplate: >>> objects = (form.DisplayForm(None, None), tableRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, ... 'display').filename '...table-form-display.pt' >>> objects = (form.DisplayForm(None, None), tableRequest) >>> zope.component.getMultiAdapter(objects, IContentTemplate, ... 'subform').filename '...subform.pt' Table ILayoutTemplate --------------------- There is one generic layout template to build sub forms: >>> objects = (form.DisplayForm(None, None), tableRequest) >>> zope.component.getMultiAdapter(objects, ILayoutTemplate, ... 'subform').filename '...subform-layout.pt' Table layout macros ------------------- We have different form macros available for IInputForm: >>> objects = (None, addForm, tableRequest) >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form') [...table-form.pt'), ...metal:define-macro': u'form'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'subform') [...table-form.pt'), ...define-macro': u'subform'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-label') [...table-form.pt'), ...define-macro': u'label'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-required-info') [...table-form.pt'), ...define-macro', u'required-info'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-header') [...table-form.pt'), ...define-macro': u'header'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-errors') [...table-form.pt'), ...define-macro': u'errors'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-table') [...table-form.pt'), ...define-macro', u'formtable'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-row') [...table-form.pt'), ...define-macro': u'formrow'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-label-cell') [...table-form.pt'), ...define-macro', u'labelcell'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-widget-cell') [...table-form.pt'), ...define-macro', u'widgetcell'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-groups') [...table-form.pt'), ...define-macro': u'groups'... >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-buttons') [...table-form.pt'), ...define-macro', u'buttons'... And we have different form macros available for IDisplayForm: >>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'subform-display') [...table-form-display.pt'), ...define-macro': u'subform-display'... Subform ------- Let's give a quick overview how subform content and layout templates get used: First define a new form which uses the template getter methods offered from z3.template >>> from z3c.template.template import getPageTemplate, getLayoutTemplate The ``provider`` TALES expression which is a part of the lookup concept was already registered by the testing setup, so we don't need to do it here. and the TALES expression called ``macro`` which can lookup our macro adapters. Yes, macros are adapters in our content/layout template concept. See z3c.macro for more information about the implementation. However, we already registered the ``macro`` type in the testing setup, as it's needed for rendering form templates. and at least we need a pagelet renderer. By default we use the provider called ``PageletRenderer`` defined in the z3c.pagelet package. But right now, we don't have a dependency on this package. So let's implement a simple renderer and use them as a IContentProvider: >>> class PageletRenderer(object): ... zope.component.adapts(zope.interface.Interface, ... zope.publisher.interfaces.browser.IBrowserRequest, ... zope.interface.Interface) ... ... def __init__(self, context, request, pagelet): ... self.__updated = False ... self.__parent__ = pagelet ... self.context = context ... self.request = request ... ... def update(self): ... pass ... ... def render(self): ... return self.__parent__.render() >>> from zope.contentprovider.interfaces import IContentProvider >>> zope.component.provideAdapter(PageletRenderer, ... provides=IContentProvider, name='pagelet') Now define the form: >>> class PersonEditForm(form.EditForm): ... """Edit form including layout support. See z3c.formui.form.""" ... ... template = getPageTemplate('subform') ... layout = getLayoutTemplate('subform') ... ... fields = field.Fields(IPerson) Now we can render the form with our previous created person instance: >>> person = Person(u'Jessy', 6) >>> editForm = PersonEditForm(person, divRequest) Now we call the form which will update and render it: >>> print(editForm()) <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <div id="form-widgets-name-row" class="row required"> <div class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required">*</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Jessy" /> </div> </div> <div id="form-widgets-age-row" class="row"> <div class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </div> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="6" /> </div> </div> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </div> You can see that the form above is a real subform. It doesn't define the form tag which makes it usable as a subform in parent forms. Of course this works with table layout based forms too. Let's use our table request and render the form again: >>> editForm = PersonEditForm(person, tableRequest) >>> print(editForm()) <div class="viewspace"> <div class="required-info"> <span class="required">*</span> &ndash; required </div> <div> <table class="form-fields"> <tr class="row required"> <td class="label"> <label for="form-widgets-name"> <span>Name</span> <span class="required"> * </span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="Jessy" /> </div> </td> </tr> <tr class="row"> <td class="label"> <label for="form-widgets-age"> <span>Age</span> </label> </td> <td class="field"> <div class="widget"><input type="text" id="form-widgets-age" name="form.widgets.age" class="text-widget int-field" value="6" /> </div> </td> </tr> </table> </div> </div> <div> <div class="buttons"> <input type="submit" id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </div> Redirection ----------- The form doesn't bother rendering itself and its layout when request is a redirection as the rendering doesn't make any sense with browser requests in that case. Let's create a view that does a redirection in its update method: >>> class RedirectingView(PersonEditForm): ... def update(self): ... super(RedirectingView, self).update() ... self.request.response.redirect('.') It will return an empty string when called as a browser page. >>> redirectView = RedirectingView(person, divRequest) >>> redirectView() == '' True However, the ``render`` method will render form's template as usual: >>> '<div class="viewspace">' in redirectView.render() True The same thing should work for AddForms: >>> class RedirectingAddView(PersonAddForm): ... def update(self): ... super(RedirectingAddView, self).update() ... self.request.response.redirect('.') >>> redirectView = RedirectingAddView(person, divRequest) >>> redirectView() == '' True No required fields ------------------ If there no required fields in the form, standard templates won't render the "required-info" hint. >>> class IAdditionalInfo(zope.interface.Interface): ... ... location = zope.schema.TextLine(title=u'Location', required=False) ... about = zope.schema.Text(title=u'About', required=False) >>> class AdditionalInfoForm(form.AddForm): ... ... fields = field.Fields(IAdditionalInfo) >>> additionalInfoForm = AdditionalInfoForm(root, divRequest) >>> additionalInfoForm.update() >>> '<div class="required-info">' in additionalInfoForm.render() False >>> additionalInfoForm = AdditionalInfoForm(root, tableRequest) >>> additionalInfoForm.update() >>> '<div class="required-info">' in additionalInfoForm.render() False Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir)
z3c.formui
/z3c.formui-4.0.tar.gz/z3c.formui-4.0/src/z3c/formui/README.txt
README.txt
from fanstatic import Library, Resource, Group from js.bootstrap import bootstrap_css, bootstrap_js library = Library('datepicker', 'resources') bootstrapdatepicker_css = Resource( library, 'bootstrap-datepicker.css', depends=[bootstrap_css], minified='bootstrap-datepicker.min.css', minifier='cssmin', ) bootstrapdatepicker_js = Resource( library, 'bootstrap-datepicker.js', depends=[bootstrap_js], minified='bootstrap-datepicker.min.js', minifier='jsmin', ) bootstrapdatepicker = Group([ bootstrapdatepicker_css, bootstrapdatepicker_js, ]) bootstrapdatepicker_bg = Resource( library, 'locales/bootstrap-datepicker.bg.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.bg.min.js', minifier='jsmin', ) bootstrapdatepicker_ca = Resource( library, 'locales/bootstrap-datepicker.ca.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.ca.min.js', minifier='jsmin', ) bootstrapdatepicker_cs = Resource( library, 'locales/bootstrap-datepicker.cs.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.cs.min.js', minifier='jsmin', ) bootstrapdatepicker_da = Resource( library, 'locales/bootstrap-datepicker.da.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.da.min.js', minifier='jsmin', ) bootstrapdatepicker_de = Resource( library, 'locales/bootstrap-datepicker.de.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.de.min.js', minifier='jsmin', ) bootstrapdatepicker_el = Resource( library, 'locales/bootstrap-datepicker.el.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.el.min.js', minifier='jsmin', ) bootstrapdatepicker_es = Resource( library, 'locales/bootstrap-datepicker.es.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.es.min.js', minifier='jsmin', ) bootstrapdatepicker_et = Resource( library, 'locales/bootstrap-datepicker.et.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.et.min.js', minifier='jsmin', ) bootstrapdatepicker_fi = Resource( library, 'locales/bootstrap-datepicker.fi.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.fi.min.js', minifier='jsmin', ) bootstrapdatepicker_fr = Resource( library, 'locales/bootstrap-datepicker.fr.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.fr.min.js', minifier='jsmin', ) bootstrapdatepicker_he = Resource( library, 'locales/bootstrap-datepicker.he.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.he.min.js', minifier='jsmin', ) bootstrapdatepicker_hr = Resource( library, 'locales/bootstrap-datepicker.hr.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.hr.min.js', minifier='jsmin', ) bootstrapdatepicker_hu = Resource( library, 'locales/bootstrap-datepicker.hu.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.hu.min.js', minifier='jsmin', ) bootstrapdatepicker_id = Resource( library, 'locales/bootstrap-datepicker.id.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.id.min.js', minifier='jsmin', ) bootstrapdatepicker_is = Resource( library, 'locales/bootstrap-datepicker.is.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.is.min.js', minifier='jsmin', ) bootstrapdatepicker_it = Resource( library, 'locales/bootstrap-datepicker.it.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.it.min.js', minifier='jsmin', ) bootstrapdatepicker_ja = Resource( library, 'locales/bootstrap-datepicker.ja.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.ja.min.js', minifier='jsmin', ) bootstrapdatepicker_kr = Resource( library, 'locales/bootstrap-datepicker.kr.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.kr.min.js', minifier='jsmin', ) bootstrapdatepicker_lt = Resource( library, 'locales/bootstrap-datepicker.lt.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.lt.min.js', minifier='jsmin', ) bootstrapdatepicker_lv = Resource( library, 'locales/bootstrap-datepicker.lv.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.lv.min.js', minifier='jsmin', ) bootstrapdatepicker_mk = Resource( library, 'locales/bootstrap-datepicker.mk.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.mk.min.js', minifier='jsmin', ) bootstrapdatepicker_ms = Resource( library, 'locales/bootstrap-datepicker.ms.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.ms.min.js', minifier='jsmin', ) bootstrapdatepicker_nb = Resource( library, 'locales/bootstrap-datepicker.nb.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.nb.min.js', minifier='jsmin', ) bootstrapdatepicker_nl = Resource( library, 'locales/bootstrap-datepicker.nl.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.nl.min.js', minifier='jsmin', ) bootstrapdatepicker_pl = Resource( library, 'locales/bootstrap-datepicker.pl.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.pl.min.js', minifier='jsmin', ) bootstrapdatepicker_pt_BR = Resource( library, 'locales/bootstrap-datepicker.pt-BR.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.pt-BR.min.js', minifier='jsmin', ) bootstrapdatepicker_pt = Resource( library, 'locales/bootstrap-datepicker.pt.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.pt.min.js', minifier='jsmin', ) bootstrapdatepicker_ro = Resource( library, 'locales/bootstrap-datepicker.ro.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.ro.min.js', minifier='jsmin', ) bootstrapdatepicker_rs_latin = Resource( library, 'locales/bootstrap-datepicker.rs-latin.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.rs-latin.min.js', minifier='jsmin', ) bootstrapdatepicker_rs = Resource( library, 'locales/bootstrap-datepicker.rs.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.rs.min.js', minifier='jsmin', ) bootstrapdatepicker_ru = Resource( library, 'locales/bootstrap-datepicker.ru.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.ru.min.js', minifier='jsmin', ) bootstrapdatepicker_sk = Resource( library, 'locales/bootstrap-datepicker.sk.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.sk.min.js', minifier='jsmin', ) bootstrapdatepicker_sl = Resource( library, 'locales/bootstrap-datepicker.sl.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.sl.min.js', minifier='jsmin', ) bootstrapdatepicker_sq = Resource( library, 'locales/bootstrap-datepicker.sq.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.sq.min.js', minifier='jsmin', ) bootstrapdatepicker_sv = Resource( library, 'locales/bootstrap-datepicker.sv.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.sv.min.js', minifier='jsmin', ) bootstrapdatepicker_sw = Resource( library, 'locales/bootstrap-datepicker.sw.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.sw.min.js', minifier='jsmin', ) bootstrapdatepicker_th = Resource( library, 'locales/bootstrap-datepicker.th.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.th.min.js', minifier='jsmin', ) bootstrapdatepicker_tr = Resource( library, 'locales/bootstrap-datepicker.tr.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.tr.min.js', minifier='jsmin', ) bootstrapdatepicker_uk = Resource( library, 'locales/bootstrap-datepicker.uk.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.uk.min.js', minifier='jsmin', ) bootstrapdatepicker_zh_CN = Resource( library, 'locales/bootstrap-datepicker.zh-CN.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.zh-CN.min.js', minifier='jsmin', ) bootstrapdatepicker_zh_TW = Resource( library, 'locales/bootstrap-datepicker.zh-TW.js', depends=[bootstrapdatepicker_js], minified='locales/bootstrap-datepicker.zh-TW.min.js', minifier='jsmin', ) bootstrapdatepicker_locales = { "bg": bootstrapdatepicker_bg, "ca": bootstrapdatepicker_ca, "cs": bootstrapdatepicker_cs, "da": bootstrapdatepicker_da, "de": bootstrapdatepicker_de, "el": bootstrapdatepicker_el, "es": bootstrapdatepicker_es, "et": bootstrapdatepicker_et, "fi": bootstrapdatepicker_fi, "fr": bootstrapdatepicker_fr, "he": bootstrapdatepicker_he, "hr": bootstrapdatepicker_hr, "hu": bootstrapdatepicker_hu, "id": bootstrapdatepicker_id, "is": bootstrapdatepicker_is, "it": bootstrapdatepicker_it, "ja": bootstrapdatepicker_ja, "kr": bootstrapdatepicker_kr, "lt": bootstrapdatepicker_lt, "lv": bootstrapdatepicker_lv, "mk": bootstrapdatepicker_mk, "ms": bootstrapdatepicker_ms, "nb": bootstrapdatepicker_nb, "nl": bootstrapdatepicker_nl, "pl": bootstrapdatepicker_pl, "pt_BR": bootstrapdatepicker_pt_BR, "pt": bootstrapdatepicker_pt, "ro": bootstrapdatepicker_ro, "rs_latin": bootstrapdatepicker_rs_latin, "rs": bootstrapdatepicker_rs, "ru": bootstrapdatepicker_ru, "sk": bootstrapdatepicker_sk, "sl": bootstrapdatepicker_sl, "sq": bootstrapdatepicker_sq, "sv": bootstrapdatepicker_sv, "sw": bootstrapdatepicker_sw, "th": bootstrapdatepicker_th, "tr": bootstrapdatepicker_tr, "uk": bootstrapdatepicker_uk, "zh_CN": bootstrapdatepicker_zh_CN, "zh_TW": bootstrapdatepicker_zh_TW, "zh": bootstrapdatepicker_zh_CN, }
z3c.formwidget.bootstrap_datepicker
/z3c.formwidget.bootstrap_datepicker-0.1.tar.gz/z3c.formwidget.bootstrap_datepicker-0.1/src/z3c/formwidget/bootstrap_datepicker/fanstaticlibs.py
fanstaticlibs.py
(function($){function UTCDate(){return new Date(Date.UTC.apply(Date,arguments));} function UTCToday(){var today=new Date();return UTCDate(today.getUTCFullYear(),today.getUTCMonth(),today.getUTCDate());} var Datepicker=function(element,options){var that=this;this._process_options(options);this.element=$(element);this.isInline=false;this.isInput=this.element.is('input');this.component=this.element.is('.date')?this.element.find('.add-on, .btn'):false;this.hasInput=this.component&&this.element.find('input').length;if(this.component&&this.component.length===0) this.component=false;this.picker=$(DPGlobal.template);this._buildEvents();this._attachEvents();if(this.isInline){this.picker.addClass('datepicker-inline').appendTo(this.element);}else{this.picker.addClass('datepicker-dropdown dropdown-menu');} if(this.o.rtl){this.picker.addClass('datepicker-rtl');this.picker.find('.prev i, .next i').toggleClass('icon-arrow-left icon-arrow-right');} this.viewMode=this.o.startView;if(this.o.calendarWeeks) this.picker.find('tfoot th.today').attr('colspan',function(i,val){return parseInt(val)+1;});this._allow_update=false;this.setStartDate(this.o.startDate);this.setEndDate(this.o.endDate);this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);this.fillDow();this.fillMonths();this._allow_update=true;this.update();this.showMode();if(this.isInline){this.show();}};Datepicker.prototype={constructor:Datepicker,_process_options:function(opts){ this._o=$.extend({},this._o,opts); var o=this.o=$.extend({},this._o); var lang=o.language;if(!dates[lang]){lang=lang.split('-')[0];if(!dates[lang]) lang=$.fn.datepicker.defaults.language;} o.language=lang;switch(o.startView){case 2:case'decade':o.startView=2;break;case 1:case'year':o.startView=1;break;default:o.startView=0;} switch(o.minViewMode){case 1:case'months':o.minViewMode=1;break;case 2:case'years':o.minViewMode=2;break;default:o.minViewMode=0;} o.startView=Math.max(o.startView,o.minViewMode);o.weekStart%=7;o.weekEnd=((o.weekStart+6)%7);var format=DPGlobal.parseFormat(o.format) if(o.startDate!==-Infinity){o.startDate=DPGlobal.parseDate(o.startDate,format,o.language);} if(o.endDate!==Infinity){o.endDate=DPGlobal.parseDate(o.endDate,format,o.language);} o.daysOfWeekDisabled=o.daysOfWeekDisabled||[];if(!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled=o.daysOfWeekDisabled.split(/[,\s]*/);o.daysOfWeekDisabled=$.map(o.daysOfWeekDisabled,function(d){return parseInt(d,10);});},_events:[],_secondaryEvents:[],_applyEvents:function(evs){for(var i=0,el,ev;i<evs.length;i++){el=evs[i][0];ev=evs[i][1];el.on(ev);}},_unapplyEvents:function(evs){for(var i=0,el,ev;i<evs.length;i++){el=evs[i][0];ev=evs[i][1];el.off(ev);}},_buildEvents:function(){if(this.isInput){ this._events=[[this.element,{focus:$.proxy(this.show,this),keyup:$.proxy(this.update,this),keydown:$.proxy(this.keydown,this)}]];} else if(this.component&&this.hasInput){ this._events=[[this.element.find('input'),{focus:$.proxy(this.show,this),keyup:$.proxy(this.update,this),keydown:$.proxy(this.keydown,this)}],[this.component,{click:$.proxy(this.show,this)}]];} else if(this.element.is('div')){ this.isInline=true;} else{this._events=[[this.element,{click:$.proxy(this.show,this)}]];} this._secondaryEvents=[[this.picker,{click:$.proxy(this.click,this)}],[$(window),{resize:$.proxy(this.place,this)}],[$(document),{mousedown:$.proxy(function(e){ if(!(this.element.is(e.target)||this.element.find(e.target).size()||this.picker.is(e.target)||this.picker.find(e.target).size())){this.hide();}},this)}]];},_attachEvents:function(){this._detachEvents();this._applyEvents(this._events);},_detachEvents:function(){this._unapplyEvents(this._events);},_attachSecondaryEvents:function(){this._detachSecondaryEvents();this._applyEvents(this._secondaryEvents);},_detachSecondaryEvents:function(){this._unapplyEvents(this._secondaryEvents);},_trigger:function(event,altdate){var date=altdate||this.date,local_date=new Date(date.getTime()+(date.getTimezoneOffset()*60000));this.element.trigger({type:event,date:local_date,format:$.proxy(function(altformat){var format=altformat||this.o.format;return DPGlobal.formatDate(date,format,this.o.language);},this)});},show:function(e){if(!this.isInline) this.picker.appendTo('body');this.picker.show();this.height=this.component?this.component.outerHeight():this.element.outerHeight();this.place();this._attachSecondaryEvents();if(e){e.preventDefault();} this._trigger('show');},hide:function(e){if(this.isInline)return;if(!this.picker.is(':visible'))return;this.picker.hide().detach();this._detachSecondaryEvents();this.viewMode=this.o.startView;this.showMode();if(this.o.forceParse&&(this.isInput&&this.element.val()||this.hasInput&&this.element.find('input').val())) this.setValue();this._trigger('hide');},remove:function(){this.hide();this._detachEvents();this._detachSecondaryEvents();this.picker.remove();delete this.element.data().datepicker;if(!this.isInput){delete this.element.data().date;}},getDate:function(){var d=this.getUTCDate();return new Date(d.getTime()+(d.getTimezoneOffset()*60000));},getUTCDate:function(){return this.date;},setDate:function(d){this.setUTCDate(new Date(d.getTime()-(d.getTimezoneOffset()*60000)));},setUTCDate:function(d){this.date=d;this.setValue();},setValue:function(){var formatted=this.getFormattedDate();if(!this.isInput){if(this.component){this.element.find('input').val(formatted);}}else{this.element.val(formatted);}},getFormattedDate:function(format){if(format===undefined) format=this.o.format;return DPGlobal.formatDate(this.date,format,this.o.language);},setStartDate:function(startDate){this._process_options({startDate:startDate});this.update();this.updateNavArrows();},setEndDate:function(endDate){this._process_options({endDate:endDate});this.update();this.updateNavArrows();},setDaysOfWeekDisabled:function(daysOfWeekDisabled){this._process_options({daysOfWeekDisabled:daysOfWeekDisabled});this.update();this.updateNavArrows();},place:function(){if(this.isInline)return;var zIndex=parseInt(this.element.parents().filter(function(){return $(this).css('z-index')!='auto';}).first().css('z-index'))+10;var offset=this.component?this.component.parent().offset():this.element.offset();var height=this.component?this.component.outerHeight(true):this.element.outerHeight(true);this.picker.css({top:offset.top+height,left:offset.left,zIndex:zIndex});},_allow_update:true,update:function(){if(!this._allow_update)return;var date,fromArgs=false;if(arguments&&arguments.length&&(typeof arguments[0]==='string'||arguments[0]instanceof Date)){date=arguments[0];fromArgs=true;}else{date=this.isInput?this.element.val():this.element.data('date')||this.element.find('input').val();delete this.element.data().date;} this.date=DPGlobal.parseDate(date,this.o.format,this.o.language);if(fromArgs)this.setValue();if(this.date<this.o.startDate){this.viewDate=new Date(this.o.startDate);}else if(this.date>this.o.endDate){this.viewDate=new Date(this.o.endDate);}else{this.viewDate=new Date(this.date);} this.fill();},fillDow:function(){var dowCnt=this.o.weekStart,html='<tr>';if(this.o.calendarWeeks){var cell='<th class="cw">&nbsp;</th>';html+=cell;this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);} while(dowCnt<this.o.weekStart+7){html+='<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';} html+='</tr>';this.picker.find('.datepicker-days thead').append(html);},fillMonths:function(){var html='',i=0;while(i<12){html+='<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';} this.picker.find('.datepicker-months td').html(html);},setRange:function(range){if(!range||!range.length) delete this.range;else this.range=$.map(range,function(d){return d.valueOf();});this.fill();},getClassNames:function(date){var cls=[],year=this.viewDate.getUTCFullYear(),month=this.viewDate.getUTCMonth(),currentDate=this.date.valueOf(),today=new Date();if(date.getUTCFullYear()<year||(date.getUTCFullYear()==year&&date.getUTCMonth()<month)){cls.push('old');}else if(date.getUTCFullYear()>year||(date.getUTCFullYear()==year&&date.getUTCMonth()>month)){cls.push('new');} if(this.o.todayHighlight&&date.getUTCFullYear()==today.getFullYear()&&date.getUTCMonth()==today.getMonth()&&date.getUTCDate()==today.getDate()){cls.push('today');} if(currentDate&&date.valueOf()==currentDate){cls.push('active');} if(date.valueOf()<this.o.startDate||date.valueOf()>this.o.endDate||$.inArray(date.getUTCDay(),this.o.daysOfWeekDisabled)!==-1){cls.push('disabled');} if(this.range){if(date>this.range[0]&&date<this.range[this.range.length-1]){cls.push('range');} if($.inArray(date.valueOf(),this.range)!=-1){cls.push('selected');}} return cls;},fill:function(){var d=new Date(this.viewDate),year=d.getUTCFullYear(),month=d.getUTCMonth(),startYear=this.o.startDate!==-Infinity?this.o.startDate.getUTCFullYear():-Infinity,startMonth=this.o.startDate!==-Infinity?this.o.startDate.getUTCMonth():-Infinity,endYear=this.o.endDate!==Infinity?this.o.endDate.getUTCFullYear():Infinity,endMonth=this.o.endDate!==Infinity?this.o.endDate.getUTCMonth():Infinity,currentDate=this.date&&this.date.valueOf(),tooltip;this.picker.find('.datepicker-days thead th.datepicker-switch').text(dates[this.o.language].months[month]+' '+year);this.picker.find('tfoot th.today').text(dates[this.o.language].today).toggle(this.o.todayBtn!==false);this.picker.find('tfoot th.clear').text(dates[this.o.language].clear).toggle(this.o.clearBtn!==false);this.updateNavArrows();this.fillMonths();var prevMonth=UTCDate(year,month-1,28,0,0,0,0),day=DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(),prevMonth.getUTCMonth());prevMonth.setUTCDate(day);prevMonth.setUTCDate(day-(prevMonth.getUTCDay()-this.o.weekStart+7)%7);var nextMonth=new Date(prevMonth);nextMonth.setUTCDate(nextMonth.getUTCDate()+42);nextMonth=nextMonth.valueOf();var html=[];var clsName;while(prevMonth.valueOf()<nextMonth){if(prevMonth.getUTCDay()==this.o.weekStart){html.push('<tr>');if(this.o.calendarWeeks){var ws=new Date(+prevMonth+(this.o.weekStart-prevMonth.getUTCDay()-7)%7*864e5), th=new Date(+ws+(7+4-ws.getUTCDay())%7*864e5), yth=new Date(+(yth=UTCDate(th.getUTCFullYear(),0,1))+(7+4-yth.getUTCDay())%7*864e5), calWeek=(th-yth)/864e5/7+1;html.push('<td class="cw">'+calWeek+'</td>');}} clsName=this.getClassNames(prevMonth);clsName.push('day');var before=this.o.beforeShowDay(prevMonth);if(before===undefined) before={};else if(typeof(before)==='boolean') before={enabled:before};else if(typeof(before)==='string') before={classes:before};if(before.enabled===false) clsName.push('disabled');if(before.classes) clsName=clsName.concat(before.classes.split(/\s+/));if(before.tooltip) tooltip=before.tooltip;clsName=$.unique(clsName);html.push('<td class="'+clsName.join(' ')+'"'+(tooltip?' title="'+tooltip+'"':'')+'>'+prevMonth.getUTCDate()+'</td>');if(prevMonth.getUTCDay()==this.o.weekEnd){html.push('</tr>');} prevMonth.setUTCDate(prevMonth.getUTCDate()+1);} this.picker.find('.datepicker-days tbody').empty().append(html.join(''));var currentYear=this.date&&this.date.getUTCFullYear();var months=this.picker.find('.datepicker-months').find('th:eq(1)').text(year).end().find('span').removeClass('active');if(currentYear&&currentYear==year){months.eq(this.date.getUTCMonth()).addClass('active');} if(year<startYear||year>endYear){months.addClass('disabled');} if(year==startYear){months.slice(0,startMonth).addClass('disabled');} if(year==endYear){months.slice(endMonth+1).addClass('disabled');} html='';year=parseInt(year/10,10)*10;var yearCont=this.picker.find('.datepicker-years').find('th:eq(1)').text(year+'-'+(year+9)).end().find('td');year-=1;for(var i=-1;i<11;i++){html+='<span class="year'+(i==-1?' old':i==10?' new':'')+(currentYear==year?' active':'')+(year<startYear||year>endYear?' disabled':'')+'">'+year+'</span>';year+=1;} yearCont.html(html);},updateNavArrows:function(){if(!this._allow_update)return;var d=new Date(this.viewDate),year=d.getUTCFullYear(),month=d.getUTCMonth();switch(this.viewMode){case 0:if(this.o.startDate!==-Infinity&&year<=this.o.startDate.getUTCFullYear()&&month<=this.o.startDate.getUTCMonth()){this.picker.find('.prev').css({visibility:'hidden'});}else{this.picker.find('.prev').css({visibility:'visible'});} if(this.o.endDate!==Infinity&&year>=this.o.endDate.getUTCFullYear()&&month>=this.o.endDate.getUTCMonth()){this.picker.find('.next').css({visibility:'hidden'});}else{this.picker.find('.next').css({visibility:'visible'});} break;case 1:case 2:if(this.o.startDate!==-Infinity&&year<=this.o.startDate.getUTCFullYear()){this.picker.find('.prev').css({visibility:'hidden'});}else{this.picker.find('.prev').css({visibility:'visible'});} if(this.o.endDate!==Infinity&&year>=this.o.endDate.getUTCFullYear()){this.picker.find('.next').css({visibility:'hidden'});}else{this.picker.find('.next').css({visibility:'visible'});} break;}},click:function(e){e.preventDefault();var target=$(e.target).closest('span, td, th');if(target.length==1){switch(target[0].nodeName.toLowerCase()){case'th':switch(target[0].className){case'datepicker-switch':this.showMode(1);break;case'prev':case'next':var dir=DPGlobal.modes[this.viewMode].navStep*(target[0].className=='prev'?-1:1);switch(this.viewMode){case 0:this.viewDate=this.moveMonth(this.viewDate,dir);break;case 1:case 2:this.viewDate=this.moveYear(this.viewDate,dir);break;} this.fill();break;case'today':var date=new Date();date=UTCDate(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);this.showMode(-2);var which=this.o.todayBtn=='linked'?null:'view';this._setDate(date,which);break;case'clear':var element;if(this.isInput) element=this.element;else if(this.component) element=this.element.find('input');if(element) element.val("").change();this._trigger('changeDate');this.update();if(this.o.autoclose) this.hide();break;} break;case'span':if(!target.is('.disabled')){this.viewDate.setUTCDate(1);if(target.is('.month')){var day=1;var month=target.parent().find('span').index(target);var year=this.viewDate.getUTCFullYear();this.viewDate.setUTCMonth(month);this._trigger('changeMonth',this.viewDate);if(this.o.minViewMode===1){this._setDate(UTCDate(year,month,day,0,0,0,0));}}else{var year=parseInt(target.text(),10)||0;var day=1;var month=0;this.viewDate.setUTCFullYear(year);this._trigger('changeYear',this.viewDate);if(this.o.minViewMode===2){this._setDate(UTCDate(year,month,day,0,0,0,0));}} this.showMode(-1);this.fill();} break;case'td':if(target.is('.day')&&!target.is('.disabled')){var day=parseInt(target.text(),10)||1;var year=this.viewDate.getUTCFullYear(),month=this.viewDate.getUTCMonth();if(target.is('.old')){if(month===0){month=11;year-=1;}else{month-=1;}}else if(target.is('.new')){if(month==11){month=0;year+=1;}else{month+=1;}} this._setDate(UTCDate(year,month,day,0,0,0,0));} break;}}},_setDate:function(date,which){if(!which||which=='date') this.date=new Date(date);if(!which||which=='view') this.viewDate=new Date(date);this.fill();this.setValue();this._trigger('changeDate');var element;if(this.isInput){element=this.element;}else if(this.component){element=this.element.find('input');} if(element){element.change();if(this.o.autoclose&&(!which||which=='date')){this.hide();}}},moveMonth:function(date,dir){if(!dir)return date;var new_date=new Date(date.valueOf()),day=new_date.getUTCDate(),month=new_date.getUTCMonth(),mag=Math.abs(dir),new_month,test;dir=dir>0?1:-1;if(mag==1){test=dir==-1 ?function(){return new_date.getUTCMonth()==month;} :function(){return new_date.getUTCMonth()!=new_month;};new_month=month+dir;new_date.setUTCMonth(new_month); if(new_month<0||new_month>11) new_month=(new_month+12)%12;}else{for(var i=0;i<mag;i++) new_date=this.moveMonth(new_date,dir); new_month=new_date.getUTCMonth();new_date.setUTCDate(day);test=function(){return new_month!=new_date.getUTCMonth();};} while(test()){new_date.setUTCDate(--day);new_date.setUTCMonth(new_month);} return new_date;},moveYear:function(date,dir){return this.moveMonth(date,dir*12);},dateWithinRange:function(date){return date>=this.o.startDate&&date<=this.o.endDate;},keydown:function(e){if(this.picker.is(':not(:visible)')){if(e.keyCode==27) this.show();return;} var dateChanged=false,dir,day,month,newDate,newViewDate;switch(e.keyCode){case 27: this.hide();e.preventDefault();break;case 37: case 39: if(!this.o.keyboardNavigation)break;dir=e.keyCode==37?-1:1;if(e.ctrlKey){newDate=this.moveYear(this.date,dir);newViewDate=this.moveYear(this.viewDate,dir);}else if(e.shiftKey){newDate=this.moveMonth(this.date,dir);newViewDate=this.moveMonth(this.viewDate,dir);}else{newDate=new Date(this.date);newDate.setUTCDate(this.date.getUTCDate()+dir);newViewDate=new Date(this.viewDate);newViewDate.setUTCDate(this.viewDate.getUTCDate()+dir);} if(this.dateWithinRange(newDate)){this.date=newDate;this.viewDate=newViewDate;this.setValue();this.update();e.preventDefault();dateChanged=true;} break;case 38: case 40: if(!this.o.keyboardNavigation)break;dir=e.keyCode==38?-1:1;if(e.ctrlKey){newDate=this.moveYear(this.date,dir);newViewDate=this.moveYear(this.viewDate,dir);}else if(e.shiftKey){newDate=this.moveMonth(this.date,dir);newViewDate=this.moveMonth(this.viewDate,dir);}else{newDate=new Date(this.date);newDate.setUTCDate(this.date.getUTCDate()+dir*7);newViewDate=new Date(this.viewDate);newViewDate.setUTCDate(this.viewDate.getUTCDate()+dir*7);} if(this.dateWithinRange(newDate)){this.date=newDate;this.viewDate=newViewDate;this.setValue();this.update();e.preventDefault();dateChanged=true;} break;case 13: this.hide();e.preventDefault();break;case 9: this.hide();break;} if(dateChanged){this._trigger('changeDate');var element;if(this.isInput){element=this.element;}else if(this.component){element=this.element.find('input');} if(element){element.change();}}},showMode:function(dir){if(dir){this.viewMode=Math.max(this.o.minViewMode,Math.min(2,this.viewMode+dir));} this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display','block');this.updateNavArrows();}};var DateRangePicker=function(element,options){this.element=$(element);this.inputs=$.map(options.inputs,function(i){return i.jquery?i[0]:i;});delete options.inputs;$(this.inputs).datepicker(options).bind('changeDate',$.proxy(this.dateUpdated,this));this.pickers=$.map(this.inputs,function(i){return $(i).data('datepicker');});this.updateDates();};DateRangePicker.prototype={updateDates:function(){this.dates=$.map(this.pickers,function(i){return i.date;});this.updateRanges();},updateRanges:function(){var range=$.map(this.dates,function(d){return d.valueOf();});$.each(this.pickers,function(i,p){p.setRange(range);});},dateUpdated:function(e){var dp=$(e.target).data('datepicker'),new_date=dp.getUTCDate(),i=$.inArray(e.target,this.inputs),l=this.inputs.length;if(i==-1)return;if(new_date<this.dates[i]){ while(i>=0&&new_date<this.dates[i]){this.pickers[i--].setUTCDate(new_date);}} else if(new_date>this.dates[i]){ while(i<l&&new_date>this.dates[i]){this.pickers[i++].setUTCDate(new_date);}} this.updateDates();},remove:function(){$.map(this.pickers,function(p){p.remove();});delete this.element.data().datepicker;}};function opts_from_el(el,prefix){ var data=$(el).data(),out={},inkey,replace=new RegExp('^'+prefix.toLowerCase()+'([A-Z])'),prefix=new RegExp('^'+prefix.toLowerCase());for(var key in data) if(prefix.test(key)){inkey=key.replace(replace,function(_,a){return a.toLowerCase();});out[inkey]=data[key];} return out;} function opts_from_locale(lang){ var out={}; if(!dates[lang]){lang=lang.split('-')[0] if(!dates[lang]) return;} var d=dates[lang];$.each($.fn.datepicker.locale_opts,function(i,k){if(k in d) out[k]=d[k];});return out;} var old=$.fn.datepicker;$.fn.datepicker=function(option){var args=Array.apply(null,arguments);args.shift();var internal_return,this_return;this.each(function(){var $this=$(this),data=$this.data('datepicker'),options=typeof option=='object'&&option;if(!data){var elopts=opts_from_el(this,'date'), xopts=$.extend({},$.fn.datepicker.defaults,elopts,options),locopts=opts_from_locale(xopts.language), opts=$.extend({},$.fn.datepicker.defaults,locopts,elopts,options);if($this.is('.input-daterange')||opts.inputs){var ropts={inputs:opts.inputs||$this.find('input').toArray()};$this.data('datepicker',(data=new DateRangePicker(this,$.extend(opts,ropts))));} else{$this.data('datepicker',(data=new Datepicker(this,opts)));}} if(typeof option=='string'&&typeof data[option]=='function'){internal_return=data[option].apply(data,args);if(internal_return!==undefined) return false;}});if(internal_return!==undefined) return internal_return;else return this;};$.fn.datepicker.defaults={autoclose:false,beforeShowDay:$.noop,calendarWeeks:false,clearBtn:false,daysOfWeekDisabled:[],endDate:Infinity,forceParse:true,format:'mm/dd/yyyy',keyboardNavigation:true,language:'en',minViewMode:0,rtl:false,startDate:-Infinity,startView:0,todayBtn:false,todayHighlight:false,weekStart:0};$.fn.datepicker.locale_opts=['format','rtl','weekStart'];$.fn.datepicker.Constructor=Datepicker;var dates=$.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa","Su"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear"}};var DPGlobal={modes:[{clsName:'days',navFnc:'Month',navStep:1},{clsName:'months',navFnc:'FullYear',navStep:1},{clsName:'years',navFnc:'FullYear',navStep:10}],isLeapYear:function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));},getDaysInMonth:function(year,month){return[31,(DPGlobal.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];},validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,parseFormat:function(format){ var separators=format.replace(this.validParts,'\0').split('\0'),parts=format.match(this.validParts);if(!separators||!separators.length||!parts||parts.length===0){throw new Error("Invalid date format.");} return{separators:separators,parts:parts};},parseDate:function(date,format,language){if(date instanceof Date)return date;if(typeof format==='string') format=DPGlobal.parseFormat(format);if(/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){var part_re=/([\-+]\d+)([dmwy])/,parts=date.match(/([\-+]\d+)([dmwy])/g),part,dir;date=new Date();for(var i=0;i<parts.length;i++){part=part_re.exec(parts[i]);dir=parseInt(part[1]);switch(part[2]){case'd':date.setUTCDate(date.getUTCDate()+dir);break;case'm':date=Datepicker.prototype.moveMonth.call(Datepicker.prototype,date,dir);break;case'w':date.setUTCDate(date.getUTCDate()+dir*7);break;case'y':date=Datepicker.prototype.moveYear.call(Datepicker.prototype,date,dir);break;}} return UTCDate(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),0,0,0);} var parts=date&&date.match(this.nonpunctuation)||[],date=new Date(),parsed={},setters_order=['yyyy','yy','M','MM','m','mm','d','dd'],setters_map={yyyy:function(d,v){return d.setUTCFullYear(v);},yy:function(d,v){return d.setUTCFullYear(2000+v);},m:function(d,v){v-=1;while(v<0)v+=12;v%=12;d.setUTCMonth(v);while(d.getUTCMonth()!=v) d.setUTCDate(d.getUTCDate()-1);return d;},d:function(d,v){return d.setUTCDate(v);}},val,filtered,part;setters_map['M']=setters_map['MM']=setters_map['mm']=setters_map['m'];setters_map['dd']=setters_map['d'];date=UTCDate(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);var fparts=format.parts.slice(); if(parts.length!=fparts.length){fparts=$(fparts).filter(function(i,p){return $.inArray(p,setters_order)!==-1;}).toArray();} if(parts.length==fparts.length){for(var i=0,cnt=fparts.length;i<cnt;i++){val=parseInt(parts[i],10);part=fparts[i];if(isNaN(val)){switch(part){case'MM':filtered=$(dates[language].months).filter(function(){var m=this.slice(0,parts[i].length),p=parts[i].slice(0,m.length);return m==p;});val=$.inArray(filtered[0],dates[language].months)+1;break;case'M':filtered=$(dates[language].monthsShort).filter(function(){var m=this.slice(0,parts[i].length),p=parts[i].slice(0,m.length);return m==p;});val=$.inArray(filtered[0],dates[language].monthsShort)+1;break;}} parsed[part]=val;} for(var i=0,s;i<setters_order.length;i++){s=setters_order[i];if(s in parsed&&!isNaN(parsed[s])) setters_map[s](date,parsed[s]);}} return date;},formatDate:function(date,format,language){if(typeof format==='string') format=DPGlobal.parseFormat(format);var val={d:date.getUTCDate(),D:dates[language].daysShort[date.getUTCDay()],DD:dates[language].days[date.getUTCDay()],m:date.getUTCMonth()+1,M:dates[language].monthsShort[date.getUTCMonth()],MM:dates[language].months[date.getUTCMonth()],yy:date.getUTCFullYear().toString().substring(2),yyyy:date.getUTCFullYear()};val.dd=(val.d<10?'0':'')+val.d;val.mm=(val.m<10?'0':'')+val.m;var date=[],seps=$.extend([],format.separators);for(var i=0,cnt=format.parts.length;i<=cnt;i++){if(seps.length) date.push(seps.shift());date.push(val[format.parts[i]]);} return date.join('');},headTemplate:'<thead>'+'<tr>'+'<th class="prev"><i class="icon-arrow-left"/></th>'+'<th colspan="5" class="datepicker-switch"></th>'+'<th class="next"><i class="icon-arrow-right"/></th>'+'</tr>'+'</thead>',contTemplate:'<tbody><tr><td colspan="7"></td></tr></tbody>',footTemplate:'<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'};DPGlobal.template='<div class="datepicker">'+'<div class="datepicker-days">'+'<table class=" table-condensed">'+ DPGlobal.headTemplate+'<tbody></tbody>'+ DPGlobal.footTemplate+'</table>'+'</div>'+'<div class="datepicker-months">'+'<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+'</table>'+'</div>'+'<div class="datepicker-years">'+'<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+'</table>'+'</div>'+'</div>';$.fn.datepicker.DPGlobal=DPGlobal;$.fn.datepicker.noConflict=function(){$.fn.datepicker=old;return this;};$(document).on('focus.datepicker.data-api click.datepicker.data-api','[data-provide="datepicker"]',function(e){var $this=$(this);if($this.data('datepicker'))return;e.preventDefault(); $this.datepicker('show');});$(function(){$('[data-provide="datepicker-inline"]').datepicker();});}(window.jQuery));
z3c.formwidget.bootstrap_datepicker
/z3c.formwidget.bootstrap_datepicker-0.1.tar.gz/z3c.formwidget.bootstrap_datepicker-0.1/src/z3c/formwidget/bootstrap_datepicker/resources/bootstrap-datepicker.min.js
bootstrap-datepicker.min.js