def __call__(self): if self.schema.getName() == "IRelatedItems": fieldset = Fieldset( "correlati", label=_("correlati_label", default="Contenuti collegati"), fields=["relatedItems"], ) self.schema._Element__tagged_values[ "plone.supermodel.fieldsets"] = [fieldset] if self.schema.getName() == "IEventBasic": fieldset = Fieldset( "date_e_orari", label=_("date_e_orari_label", default="Date e orari"), fields=["start", "end", "whole_day", "open_end", "sync_uid"], ) self.schema._Element__tagged_values[ "plone.supermodel.fieldsets"] = [fieldset] if self.schema.getName() == "IEventRecurrence": fieldset = Fieldset( "date_e_orari", label=_("date_e_orari_label", default="Date e orari"), fields=["recurrence"], ) self.schema._Element__tagged_values[ "plone.supermodel.fieldsets"] = [fieldset]
def factory(self, name, label=None, description=None, fields=None, **kw): fieldset = Fieldset(name, label=label, description=description, fields=fields) for (key, value) in kw.items(): setattr(fieldset, key, value) return [fieldset]
def generateInterface(self): logger.debug("generating interface for %s" % self.short_name) if hasattr(self, "is_single_select") and self.is_single_select: select_field = schema.Choice( title=_(safe_unicode(self.field_title)), description=_(safe_unicode(self.field_description)), required=self.is_required, vocabulary=self.vocabulary_name, ) else: select_field = schema.List( title=_(safe_unicode(self.field_title)), description=_(safe_unicode(self.field_description)), required=self.is_required, min_length=self.is_required and 1 or 0, value_type=schema.Choice( vocabulary=self.vocabulary_name, required=self.is_required ), ) schemaclass = SchemaClass( self.short_name, (Schema,), __module__="collective.taxonomy.generated", attrs={str(self.field_name): select_field}, ) if self.write_permission: schemaclass.setTaggedValue( WRITE_PERMISSIONS_KEY, {self.field_name: self.write_permission} ) try: taxonomy_fieldset = self.taxonomy_fieldset except AttributeError: # Backwards compatible: taxonomy_fieldset = "categorization" if taxonomy_fieldset != "default": schemaclass.setTaggedValue( FIELDSETS_KEY, [Fieldset(taxonomy_fieldset, fields=[self.field_name])] ) if hasattr(self, "is_single_select") and not self.is_single_select: schemaclass.setTaggedValue( WIDGETS_KEY, { self.field_name: "collective.taxonomy.widget.TaxonomySelectFieldWidget" }, ) alsoProvides(schemaclass, IFormFieldProvider) if HAS_PAM: alsoProvides(schemaclass[self.field_name], ILanguageIndependentField) return schemaclass
def generateInterface(self): logger.debug('generating interface for %s' % self.short_name) if hasattr(self, 'is_single_select') and self.is_single_select: select_field = schema.Choice(title=_(unicode(self.field_title)), description=_( unicode(self.field_description)), required=self.is_required, vocabulary=self.vocabulary_name) else: select_field = schema.List( title=_(unicode(self.field_title)), description=_(unicode(self.field_description)), required=self.is_required, min_length=self.is_required and 1 or 0, value_type=schema.Choice(vocabulary=self.vocabulary_name, required=self.is_required)) schemaclass = SchemaClass(self.short_name, (Schema, ), __module__='collective.taxonomy.generated', attrs={str(self.field_name): select_field}) if self.write_permission: schemaclass.setTaggedValue( WRITE_PERMISSIONS_KEY, {self.field_name: self.write_permission}) schemaclass.setTaggedValue(FIELDSETS_KEY, [ Fieldset('categorization', label=_pmf(u'label_schema_categorization', default=u'Categorization'), fields=[self.field_name]) ]) # if hasattr(self, 'is_single_select') and not self.is_single_select: # schemaclass.setTaggedValue( # WIDGETS_KEY, # {self.field_name: # 'collective.taxonomy.widget.TaxonomySelectFieldWidget'} # ) if hasattr(self, 'is_single_select') and not self.is_single_select: if hasattr(self, 'has_query_widget') and self.has_query_widget: schemaclass.setTaggedValue( WIDGETS_KEY, { self.field_name: 'plone.formwidget.autocomplete.widget.AutocompleteMultiFieldWidget' }) else: schemaclass.setTaggedValue( WIDGETS_KEY, { self.field_name: 'collective.taxonomy.widget.TaxonomySelectFieldWidget' }) alsoProvides(schemaclass, IFormFieldProvider) return schemaclass
def test_processFields_fieldsets_as_form_groups(self): form = Form(None, None) form.groups = [] class schema(Interface): title = zope.schema.TextLine() fieldset = Fieldset('custom', label=u'Custom', fields=['title']) schema.setTaggedValue(FIELDSETS_KEY, [fieldset]) class subschema(schema): subtitle = zope.schema.TextLine() fieldset = Fieldset('custom', label=u'Custom', fields=['subtitle']) subschema.setTaggedValue(FIELDSETS_KEY, [fieldset]) processFields(form, subschema, prefix='prefix', permissionChecks=True) self.assertEqual(len(form.groups), 1) self.assertEqual(len(form.groups[0].fields), 2) self.assertEqual([g.__name__ for g in form.groups], ['custom'])
def test_fieldset_configuration(self): """Test, if fieldsets can be orderd via fieldset configuration on a schema without fields. This schema should also not be included in form groups. """ form = Form(None, None) form.groups = [] class schema1(Interface): title = zope.schema.TextLine() fs1 = Fieldset('fs1', label=u'fs1', fields=['title']) schema1.setTaggedValue(FIELDSETS_KEY, [fs1]) class schema2(Interface): subtitle = zope.schema.TextLine() fs2 = Fieldset('fs2', label=u'fs2', fields=['subtitle']) schema2.setTaggedValue(FIELDSETS_KEY, [fs2]) class schema3(Interface): pass fs3 = Fieldset('fs1', order=2) fs4 = Fieldset('fs2', order=1) schema3.setTaggedValue(FIELDSETS_KEY, [fs3, fs4]) processFields(form, schema1, prefix='prefix', permissionChecks=True) processFields(form, schema2, prefix='prefix', permissionChecks=True) processFields(form, schema3, prefix='prefix', permissionChecks=True) self.assertEqual(len(form.groups), 2) self.assertEqual(form.groups[0].__name__, 'fs1') self.assertEqual(form.groups[0].order, 2) self.assertEqual(form.groups[1].__name__, 'fs2') self.assertEqual(form.groups[1].order, 1)
def generateInterface(self): logger.debug('generating interface for %s' % self.short_name) if hasattr(self, 'is_single_select') and self.is_single_select: select_field = schema.Choice(title=_(unicode(self.field_title)), description=_( unicode(self.field_description)), required=self.is_required, vocabulary=self.vocabulary_name) else: select_field = schema.List( title=_(unicode(self.field_title)), description=_(unicode(self.field_description)), required=self.is_required, min_length=self.is_required and 1 or 0, value_type=schema.Choice(vocabulary=self.vocabulary_name, required=self.is_required)) schemaclass = SchemaClass(self.short_name, (Schema, ), __module__='collective.taxonomy.generated', attrs={str(self.field_name): select_field}) if self.write_permission: schemaclass.setTaggedValue( WRITE_PERMISSIONS_KEY, {self.field_name: self.write_permission}) try: taxonomy_fieldset = self.taxonomy_fieldset except AttributeError: # Backwards compatible: taxonomy_fieldset = 'categorization' if taxonomy_fieldset != 'default': schemaclass.setTaggedValue( FIELDSETS_KEY, [Fieldset(taxonomy_fieldset, fields=[self.field_name])]) if hasattr(self, 'is_single_select') and not self.is_single_select: schemaclass.setTaggedValue( WIDGETS_KEY, { self.field_name: 'collective.taxonomy.widget.TaxonomySelectFieldWidget' }) alsoProvides(schemaclass, IFormFieldProvider) return schemaclass
from zope.globalrequest import getRequest from zope.interface import implements from zope.interface import Interface from zope.interface import Invalid from zope.interface import invariant from zope.intid.interfaces import IIntIds import logging import os.path LOG = logging.getLogger('opengever.document') MAIL_EXTENSIONS = ['.eml', '.msg', '.p7m'] # move the changeNote to the 'common' fieldset IVersionable.setTaggedValue(FIELDSETS_KEY, [Fieldset('common', fields=[ 'changeNote', ])]) # omit the changeNote from all forms because it's not possible to create a new # version when editing document metadata IVersionable.setTaggedValue(OMITTED_KEY, [(Interface, 'changeNote', 'true'), (IEditForm, 'changeNote', 'true'), (IAddForm, 'changeNote', 'true')]) class IDocumentSchema(model.Schema): """Document Schema Interface.""" model.fieldset( u'common', label=_(u'fieldset_common', u'Common'),
def create(self, data): return Fieldset(**data)
from plone.supermodel.model import Fieldset class IRelatedOffice(model.Schema): ''' Behavior interface ''' form.widget(related_office=MultiContentTreeFieldWidget) related_office = RelationList( title=_(u'label_related_office', default=u'Related office'), default=[], value_type=RelationChoice( title=u"Related", source=ObjPathSourceBinder( object_provides=IUfficio.__identifier__), ), required=False ) fieldset = Fieldset('categorization', label=_(u'Categorization'), fields=['related_office']) IRelatedOffice.setTaggedValue(FIELDSETS_KEY, [fieldset]) class RelatedOffice(model.Schema): ''' Behavior interface ''' alsoProvides(IRelatedOffice, IFormFieldProvider)
from z3c.relationfield.schema import RelationChoice, RelationList from plone.formwidget.contenttree import ObjPathSourceBinder from plone.supermodel.interfaces import FIELDSETS_KEY from plone.supermodel.model import Fieldset from plone.autoform.interfaces import IFormFieldProvider try: from plone.app.dexterity import MessageFactory as _ except ImportError: _ = unicode class IRelatedItems(Interface): """Behavior interface to make a Dexterity type support related items. """ relatedItems = RelationList( title=_(u'label_related_items', default=u'Related Items'), default=[], value_type=RelationChoice(title=u"Related", source=ObjPathSourceBinder()), required=False, ) fieldset = Fieldset('categorization', label=_(u'Categorization'), fields=['relatedItems']) IRelatedItems.setTaggedValue(FIELDSETS_KEY, [fieldset]) alsoProvides(IRelatedItems, IFormFieldProvider)
if HAVE_BLOBS: from plone.namedfile import NamedBlobFile as NamedFile else: from plone.namedfile import NamedFile MESSAGE_SOURCE_DRAG_DROP_UPLOAD = 'upload' MESSAGE_SOURCE_MAILIN = 'mailin' NO_SUBJECT_FALLBACK_ID = 'no_subject' NO_SUBJECT_TITLE_FALLBACK = '[No Subject]' IMail.setTaggedValue(FIELDSETS_KEY, [ Fieldset('common', label=base_mf(u'fieldset_common', u'Common'), fields=[u'message']) ]) class IOGMailMarker(Interface): """Marker Interface for opengever mails.""" def get_message_source_vocabulary(): terms = [ SimpleTerm(MESSAGE_SOURCE_MAILIN, title=_('label_message_source_mailin', default='Mail-in')), SimpleTerm(MESSAGE_SOURCE_DRAG_DROP_UPLOAD, title=_('label_message_source_d_n_d_upload',
def _parse(source, policy): tree = etree.parse(source) root = tree.getroot() parseinfo.i18n_domain = root.attrib.get(ns('domain', prefix=I18N_NAMESPACE)) model = Model() handlers = {} schema_metadata_handlers = tuple(getUtilitiesFor(ISchemaMetadataHandler)) field_metadata_handlers = tuple(getUtilitiesFor(IFieldMetadataHandler)) policy_util = getUtility(ISchemaPolicy, name=policy) def readField(fieldElement, schemaAttributes, fieldElements, baseFields): # Parse field attributes fieldName = fieldElement.get('name') fieldType = fieldElement.get('type') if fieldName is None or fieldType is None: raise ValueError( 'The attributes \'name\' and \'type\' are required for each ' '<field /> element') handler = handlers.get(fieldType, None) if handler is None: handler = handlers[fieldType] = queryUtility( IFieldExportImportHandler, name=fieldType) if handler is None: raise ValueError( 'Field type {0} specified for field {1} is not ' 'supported'.format(fieldType, fieldName)) field = handler.read(fieldElement) # Preserve order from base interfaces if this field is an override # of a field with the same name in a base interface base_field = baseFields.get(fieldName, None) if base_field is not None: field.order = base_field.order # Save for the schema schemaAttributes[fieldName] = field fieldElements[fieldName] = fieldElement return fieldName for schema_element in root.findall(ns('schema')): parseinfo.stack.append(schema_element) schemaAttributes = {} schemaName = schema_element.get('name') if schemaName is None: schemaName = u"" bases = () baseFields = {} based_on = schema_element.get('based-on') if based_on is not None: bases = tuple([resolve(dotted) for dotted in based_on.split()]) for base_schema in bases: baseFields.update(getFields(base_schema)) fieldElements = {} # Read global fields for fieldElement in schema_element.findall(ns('field')): parseinfo.stack.append(fieldElement) readField(fieldElement, schemaAttributes, fieldElements, baseFields) parseinfo.stack.pop() # Read invariants, fieldsets and their fields invariants = [] fieldsets = [] fieldsets_by_name = {} for subelement in schema_element: parseinfo.stack.append(subelement) if subelement.tag == ns('field'): readField(subelement, schemaAttributes, fieldElements, baseFields) elif subelement.tag == ns('fieldset'): fieldset_name = subelement.get('name') if fieldset_name is None: raise ValueError( u'Fieldset in schema {0} has no name'.format( schemaName)) fieldset = fieldsets_by_name.get(fieldset_name, None) if fieldset is None: fieldset_label = subelement.get('label') fieldset_description = subelement.get('description') fieldset_order = subelement.get('order') if fieldset_order is None: fieldset_order = DEFAULT_ORDER elif isinstance(fieldset_order, six.string_types): fieldset_order = int(fieldset_order) fieldset = fieldsets_by_name[fieldset_name] = Fieldset( fieldset_name, label=fieldset_label, description=fieldset_description, order=fieldset_order, ) fieldsets_by_name[fieldset_name] = fieldset fieldsets.append(fieldset) for fieldElement in subelement.findall(ns('field')): parseinfo.stack.append(fieldElement) parsed_fieldName = readField(fieldElement, schemaAttributes, fieldElements, baseFields) if parsed_fieldName: fieldset.fields.append(parsed_fieldName) parseinfo.stack.pop() elif subelement.tag == ns('invariant'): dotted = subelement.text invariant = resolve(dotted) if not IInvariant.providedBy(invariant): raise ImportError( u'Invariant functions must provide ' u'plone.supermodel.interfaces.IInvariant') invariants.append(invariant) parseinfo.stack.pop() schema = SchemaClass(name=policy_util.name(schemaName, tree), bases=bases + policy_util.bases(schemaName, tree) + (Schema, ), __module__=policy_util.module(schemaName, tree), attrs=schemaAttributes) # add invariants to schema as tagged values if invariants: schema_invariants = schema.queryTaggedValue('invariants', []) schema.setTaggedValue('invariants', schema_invariants + invariants) # Save fieldsets schema.setTaggedValue(FIELDSETS_KEY, fieldsets) # Let metadata handlers write metadata for handler_name, metadata_handler in field_metadata_handlers: for fieldName in schema: if fieldName in fieldElements: metadata_handler.read(fieldElements[fieldName], schema, schema[fieldName]) for handler_name, metadata_handler in schema_metadata_handlers: metadata_handler.read(schema_element, schema) model.schemata[schemaName] = schema parseinfo.stack.pop() parseinfo.i18n_domain = None return model
def parse(source, policy=u""): tree = ElementTree.parse(source) root = tree.getroot() model = Model() handlers = {} schema_metadata_handlers = tuple(getUtilitiesFor(ISchemaMetadataHandler)) field_metadata_handlers = tuple(getUtilitiesFor(IFieldMetadataHandler)) policy_util = getUtility(ISchemaPolicy, name=policy) def readField(fieldElement, schemaAttributes, fieldElements, baseFields): # Parse field attributes fieldName = fieldElement.get('name') fieldType = fieldElement.get('type') if fieldName is None or fieldType is None: raise ValueError("The attributes 'name' and 'type' are required for each <field /> element") handler = handlers.get(fieldType, None) if handler is None: handler = handlers[fieldType] = queryUtility(IFieldExportImportHandler, name=fieldType) if handler is None: raise ValueError("Field type %s specified for field %s is not supported" % (fieldType, fieldName, )) field = handler.read(fieldElement) # Preserve order from base interfaces if this field is an override # of a field with the same name in a base interface base_field = baseFields.get(fieldName, None) if base_field is not None: field.order = base_field.order # Save for the schema schemaAttributes[fieldName] = field fieldElements[fieldName] = fieldElement return fieldName for schema_element in root.findall(ns('schema')): schemaAttributes = {} schema_metadata = {} schemaName = schema_element.get('name') if schemaName is None: schemaName = u"" bases = () baseFields = {} based_on = schema_element.get('based-on') if based_on is not None: bases = tuple([resolve(dotted) for dotted in based_on.split()]) for base_schema in bases: baseFields.update(getFields(base_schema)) fieldElements = {} # Read global fields for fieldElement in schema_element.findall(ns('field')): readField(fieldElement, schemaAttributes, fieldElements, baseFields) # Read fieldsets and their fields fieldsets = [] fieldsets_by_name = {} for subelement in schema_element: if subelement.tag == ns('field'): readField(subelement, schemaAttributes, fieldElements, baseFields) elif subelement.tag == ns('fieldset'): fieldset_name = subelement.get('name') if fieldset_name is None: raise ValueError(u"Fieldset in schema %s has no name" % (schemaName)) fieldset = fieldsets_by_name.get(fieldset_name, None) if fieldset is None: fieldset_label = subelement.get('label') fieldset_description = subelement.get('description') fieldset = fieldsets_by_name[fieldset_name] = Fieldset(fieldset_name, label=fieldset_label, description=fieldset_description) fieldsets_by_name[fieldset_name] = fieldset fieldsets.append(fieldset) for fieldElement in subelement.findall(ns('field')): parsed_fieldName = readField(fieldElement, schemaAttributes, fieldElements, baseFields) if parsed_fieldName: fieldset.fields.append(parsed_fieldName) schema = InterfaceClass(name=policy_util.name(schemaName, tree), bases=bases + policy_util.bases(schemaName, tree), __module__=policy_util.module(schemaName, tree), attrs=schemaAttributes) schema.setTaggedValue(FIELDSETS_KEY, fieldsets) # Save fieldsets # Let metadata handlers write metadata for handler_name, metadata_handler in field_metadata_handlers: for fieldName in schema: if fieldName in fieldElements: metadata_handler.read(fieldElements[fieldName], schema, schema[fieldName]) for handler_name, metadata_handler in schema_metadata_handlers: metadata_handler.read(schema_element, schema) model.schemata[schemaName] = schema return model
}, ) IFeedControl.setTaggedValue( OMITTED_KEY, ( (IAutoExtensibleForm, 'feeds', settings_available), (IAutoExtensibleForm, 'feedModerate', settings_available), (IAutoExtensibleForm, 'feedSchedule', settings_available), (IAutoExtensibleForm, 'feedModerate', moderation_enabled), ) ) IFeedControl.setTaggedValue( FIELDSETS_KEY, [Fieldset( 'dates', fields=['feedSchedule', 'feedModerate'], label=_(u"Dates")), Fieldset( 'categorization', fields=['feeds'], label=_(u"Categorization")), ] ) IFeedControl.setTaggedValue( WIDGETS_KEY, {'feeds': 'z3c.form.browser.checkbox.CheckBoxFieldWidget'} )