def _Vocabulary(self, content_instance): pairs = [] pc = getToolByName(content_instance, 'portal_catalog') allowed_types = self.allowed_types allowed_types_method = getattr(self, 'allowed_types_method', None) if allowed_types_method: meth = getattr(content_instance, allowed_types_method) allowed_types = meth(self) skw = allowed_types and {'portal_type': allowed_types} or {} pc_brains = pc.searchResults(**skw) if self.vocabulary_custom_label is not None: label = lambda b: eval(self.vocabulary_custom_label, {'b': b}) elif self.vocabulary_display_path_bound != -1 and len( pc_brains) > self.vocabulary_display_path_bound: at = _(u'label_at', default=u'at') label = lambda b: u'%s %s %s' % (self._brains_title_or_id( b, content_instance), at, b.getPath()) else: label = lambda b: self._brains_title_or_id(b, content_instance) for b in pc_brains: pairs.append((str(b.intid), label(b))) if not self.required and not self.multiValued: no_reference = _(u'label_no_reference', default=u'<no reference>') pairs.insert(0, ('', no_reference)) __traceback_info__ = (content_instance, self.getName(), pairs) __traceback_info__ # pyflakes return DisplayList(pairs)
def _Vocabulary(self, content_instance): pairs = [] pc = getToolByName(content_instance, 'portal_catalog') allowed_types = self.allowed_types allowed_types_method = getattr(self, 'allowed_types_method', None) if allowed_types_method: meth = getattr(content_instance, allowed_types_method) allowed_types = meth(self) skw = allowed_types and {'portal_type': allowed_types} or {} pc_brains = pc.searchResults(**skw) if self.vocabulary_custom_label is not None: label = lambda b: eval(self.vocabulary_custom_label, {'b': b}) elif self.vocabulary_display_path_bound != -1 and len( pc_brains) > self.vocabulary_display_path_bound: at = _(u'label_at', default=u'at') label = lambda b: u'%s %s %s' % ( self._brains_title_or_id(b, content_instance), at, b.getPath()) else: label = lambda b: self._brains_title_or_id(b, content_instance) for b in pc_brains: pairs.append((str(b.intid), label(b))) if not self.required and not self.multiValued: no_reference = _(u'label_no_reference', default=u'<no reference>') pairs.insert(0, ('', no_reference)) __traceback_info__ = (content_instance, self.getName(), pairs) __traceback_info__ # pyflakes return DisplayList(pairs)
def languages(self): """Vocabulary method for the language field """ util = None use_combined = False # Respect the combined language code setting from PloneLanguageTool lt = getToolByName(self, "portal_languages", None) if lt is not None: use_combined = lt.use_combined_language_codes # Try the utility first if HAS_PLONE_I18N: util = queryUtility(IMetadataLanguageAvailability) # Fall back to acquiring availableLanguages if util is None: languages = getattr(self, "availableLanguages", None) if callable(languages): languages = languages() # Fall back to static definition if languages is None: return DisplayList( (("en", "English"), ("fr", "French"), ("es", "Spanish"), ("pt", "Portuguese"), ("ru", "Russian")) ) else: languages = util.getLanguageListing(combined=use_combined) languages.sort(key=lambda x: x[1]) # Put language neutral at the top. languages.insert(0, (u"", _(u"Language neutral"))) return DisplayList(languages)
def languages(self): """Vocabulary method for the language field """ util = None use_combined = False # Respect the combined language code setting from PloneLanguageTool lt = getToolByName(self, 'portal_languages', None) if lt is not None: use_combined = lt.use_combined_language_codes # Try the utility first if HAS_PLONE_I18N: util = queryUtility(IMetadataLanguageAvailability) # Fall back to acquiring availableLanguages if util is None: languages = getattr(self, 'availableLanguages', None) if callable(languages): languages = languages() # Fall back to static definition if languages is None: return DisplayList( (('en', 'English'), ('fr', 'French'), ('es', 'Spanish'), ('pt', 'Portuguese'), ('ru', 'Russian'))) else: languages = util.getLanguageListing(combined=use_combined) languages.sort(key=lambda x: x[1]) # Put language neutral at the top. languages.insert(0, (u'', _(u'Language neutral'))) return DisplayList(languages)
def validate_content_types(self, instance, value, errors): """make sure the value's content-type is allowed""" if value in ("DELETE_IMAGE", "DELETE_FILE", None, ''): return None # plone.app.blob.field.BlobWrapper cannot be imported # at startup due to circular imports from plone.app.blob.field import BlobWrapper body = '' if isinstance(value, FileType): tell = value.tell() value.seek(0) body = value.read() value.seek(tell) elif isinstance(value, StringType): body = value elif isinstance(value, BlobWrapper): body = value.data if isinstance(value, (FileType, BlobWrapper)) and body in (None, ''): return None mtr = getToolByName(instance, 'mimetypes_registry', None) if mtr is not None: orig_filename = getattr(value, 'filename', getattr(value, 'name', '')) kw = dict(mimetype=None, filename=orig_filename) try: d, f, mimetype = mtr(body[:8096], **kw) except UnicodeDecodeError: d, f, mimetype = mtr(len(body) < 8096 and body or '', **kw) else: mimetype, enc = guess_content_type( value.filename, value.read(), None) mimetype = str(mimetype).split(';')[0].strip() if mimetype not in self.allowable_content_types: request = aq_get(instance, 'REQUEST') label = self.widget.Label(instance) name = self.getName() if isinstance(label, Message): label = translate(label, context=request) error = _(u'error_allowable_content_types', default=u'Mimetype ${mimetype} is not allowed ' 'on ${name}, please correct.', mapping={ 'mimetype': mimetype, 'name': label }) error = translate(error, context=request) errors[name] = error return error return
def __call__(self): self.processed = False self.errors = {} start_time = self.context.ZopeTime().timeTime() if not self.request.form.get('form.submitted'): return self.template() # fetch value from request input_encoding = self.request.form.get('input_encoding', 'utf-8') span_of_search = self.request.form.get('span_of_search', None) format = self.request.form.get('format', 'bib') # process source filename = None source = self.request.form.get('up_text') if not source: upfile = self.request.form.get('file') filename = upfile and getattr(upfile, 'filename', None) if not filename: self.errors['file'] = _(u'You must import a file or enter a' ' text.') addStatusMessage(self.request, _(u"Please correct the indicated errors.")) return self.template() source = upfile.read() if not source or not isinstance(source, basestring): msg = "Could not read the file '%s'." % filename self.errors['file'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() # skip DOS line breaks source = source.replace('\r', '') # get parsed entries from the Bibliography Tool bibtool = getToolByName(self.context, 'portal_bibliography') try: entries = bibtool.getEntries(source, format, filename, input_encoding=input_encoding) except ImportParseError: msg = """%s Parser's 'checkFormat' and guessing the format""" \ """ from the file name '%s' failed.""" % (format, filename) self.errors['format'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except UnicodeError: msg = """The choosen input encoding does not match the real """ \ """encoding of your input data in order to convert it to """\ """unicode internally.""" self.errors['input_encoding'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except RuntimeError, e: addStatusMessage(self.request, _(unicode(e))) return self.template()
def finalizeSchema(baseSchema, type='None', non_exclude_schematas=[], non_exclude_fields=[]): newSchema = baseSchema newSchema['id'].required = 1 #olhar essa questao da permissao posteriormente #newSchema['id'].read_permission = VIEW_PATIENT #newSchema['id'].write_permission = EDIT_PATIENT newSchema['id'].schemata = 'main' newSchema['id'].widget = IdWidget(label='User Id', label_msgid='cmfuemr_label_user_id', i18n_domain='cmfuemr', visible={ 'edit': 'invisible', 'view': 'invisible' }) newSchema['description'].widget = TextAreaWidget( label=_(u'label_description', default=u'Description'), description=_(u'help_description', default=u'Used in item listings and search results.'), rows='2', ) #- Esconde os fields dos schematas default, categorization, dates, ownership #---------------------------------------------------------------- e settings # Esconde os fields dos schematas default, categorization, date, ownership # e settings. if type == 'Visit': fields = newSchema.getSchemataFields('default') for field in fields: field_name = field.getName() if field_name is not 'startDate' and field_name is not 'endDate': field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } else: if field_name is 'startDate': field.widget.label = u'Início da Consulta' else: field.required = False field.widget.label = u'Final da Consulta' field.default_method = endDateDefaultMethod field.widget.visible = { 'edit': 'visible', 'view': 'visible' } else: if 'default' not in non_exclude_schematas: newSchema['title'].required = 0 # newSchema['title'].searchable = 0 # newSchema['title'].schemata = 'main' # newSchema['title'].widget = StringWidget(visible={'edit':'invisible', # 'view':'invisible'}, # label='title', # label_msgid='cmfuemr_label_title', # i18n_domain='cmfuemr') #newSchema['description'].searchable = 0 fields = newSchema.getSchemataFields('default') for field in fields: if field not in non_exclude_fields: field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } if 'categorization' not in non_exclude_schematas: fields = newSchema.getSchemataFields('categorization') for field in fields: if field not in non_exclude_fields: field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } if 'dates' not in non_exclude_schematas: fields = newSchema.getSchemataFields('dates') if field not in non_exclude_fields: for field in fields: field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } if 'ownership' not in non_exclude_schematas: fields = newSchema.getSchemataFields('ownership') if field not in non_exclude_fields: for field in fields: field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } if 'settings' not in non_exclude_schematas: fields = newSchema.getSchemataFields('settings') if field not in non_exclude_fields: for field in fields: field.widget.visible = { 'edit': 'invisible', 'view': 'invisible' } return newSchema
subfields = ('label', 'value'), subfield_labels ={'label':'Identifier'}, subfield_vocabularies = {'label':'publicationIdentifiers',}, widget=RecordsWidget( i18n_domain = "cmfbibliographyat", label = u"Identifiers", ), ), LinesField('keywords', searchable=1, required=0, languageIndependent=1, is_duplicates_criterion=False, multiValued=1, widget=KeywordWidget( label=_(u'label_keywords', default=u'Keywords'), description=_(u'help_keywords', default=u'Categorization of the publications content.'), i18n_domain = "cmfbibliographyat", ), ), StringField('publication_month', searchable=1, required=0, languageIndependent=1, is_duplicates_criterion=True, widget=StringWidget( label="Publication Month", label_msgid="label_publication_month", description_msgid="help_publication_month", description="Month of publication (or writing, if not published).",
def getTranslatedSchemaLabel(self, schema): label = u"label_schema_%s" % schema default = unicode(schema).capitalize() return _(label, default=default)
from Products.Archetypes.tests.utils import mkDummyInContext from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes import atapi class DummyDiscussionTool: def isDiscussionAllowedFor(self, content): return False def overrideDiscussionFor(self, content, allowDiscussion): pass MULTIPLEFIELD_LIST = atapi.DisplayList( ( ('1', _(u'Option 1 : printemps')), ('2', unicode('Option 2 : \xc3\xa9t\xc3\xa9', 'utf-8')), # e-acute t e-acute ('3', u'Option 3 : automne'), ('4', _(u'option3', default=u'Option 3 : hiver')), )) schema = atapi.BaseSchema + atapi.Schema(( atapi.LinesField( 'MULTIPLEFIELD', searchable=1, vocabulary=MULTIPLEFIELD_LIST, widget=atapi.MultiSelectionWidget( i18n_domain='plone', ), ), atapi.TextField(
from Products.Archetypes.tests.utils import mkDummyInContext from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes import atapi class DummyDiscussionTool: def isDiscussionAllowedFor(self, content): return False def overrideDiscussionFor(self, content, allowDiscussion): pass MULTIPLEFIELD_LIST = atapi.DisplayList(( ('1', _(u'Option 1 : printemps')), ('2', unicode('Option 2 : \xc3\xa9t\xc3\xa9', 'utf-8')), # e-acute t e-acute ('3', u'Option 3 : automne'), ('4', _(u'option3', default=u'Option 3 : hiver')), )) schema = atapi.BaseSchema + atapi.Schema(( atapi.LinesField( 'MULTIPLEFIELD', searchable=1, vocabulary=MULTIPLEFIELD_LIST, widget=atapi.MultiSelectionWidget(i18n_domain='plone', ), ), atapi.TextField( 'TEXTFIELD',
## Script (Python) "rejectAnonymous" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes.utils import addStatusMessage if context.portal_membership.isAnonymousUser(): url = '%s/login_form' % context.portal_url() addStatusMessage(REQUEST, _(u'You must sign in first.'), type='info') RESPONSE=context.REQUEST.RESPONSE return RESPONSE.redirect(url) return True
_marker = [] content_type = Schema(( StringField( name='id', required=0, # Still actually required, but the widget will # supply the missing value on non-submits mode='rw', permission=permission_copy_or_move, accessor='getId', mutator='setId', default=None, widget=IdWidget( label=_(u'label_short_name', default=u'Short name'), description=_(u'help_shortname', default=u'Should not contain spaces, underscores or mixed case. ' 'Short Name is part of the item\'s web address.'), visible={'view': 'invisible'} ), ), StringField( name='title', required=1, searchable=1, default='', accessor='Title', widget=StringWidget( label_msgid='label_title',
## Script (Python) "rejectAnonymous" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes.utils import addStatusMessage if context.portal_membership.isAnonymousUser(): url = '%s/login_form' % context.portal_url() addStatusMessage(REQUEST, _(u'You must sign in first.'), type='info') RESPONSE = context.REQUEST.RESPONSE return RESPONSE.redirect(url) return True
destination='getPdfFolderPath', startup_directory_method='getPdfFolderPath', i18n_domain="cmfbibliographyat", visible={ 'edit': 'visible', 'view': 'invisible', }, condition= "python: object.portal_membership.checkPermission('ManagePortal', object)", pattern_options={ 'basePath': '', "contextPath": None, 'selectableTypes': [ 'PDF File', ], 'placeholder': _(u'Begin typing a name'), }, ), ), FileField( 'uploaded_pdfFile', schemata="full text", languageIndependent=True, default_content_type="application/pdf", mutator='setUploaded_pdfFile', edit_accessor='editUploaded_pdfFile', accessor='getUploaded_pdfFile', #validators = (('isNonEmptyFile', V_REQUIRED),), widget=FileWidget( label="Printable PDF File", label_msgid="label_upload_pdffile_from_bibrefitem",
from AccessControl import ClassSecurityInfo from App.class_init import InitializeClass from Acquisition import aq_base from Acquisition import aq_inner from ExtensionClass import Base from zope.interface import implements TemplateMixinSchema = Schema(( # TemplateMixin StringField( 'layout', write_permission=permissions.ModifyPortalContent, default_method="getDefaultLayout", vocabulary="_voc_templates", widget=SelectionWidget( label=_(u'label_template_mixin', default=u'View template'), description=_( u'help_template_mixin', default= u'Choose a template that will be used for viewing this item.'), visible={ 'view': 'hidden', 'edit': 'visible' }, )), )) class TemplateMixin(Base): implements(ITemplateMixin) schema = TemplateMixinSchema
# make the description field of NewsItems render HTML description = TextField('description', required=False, searchable=True, accessor="Description", mutator='setDescription', edit_accessor="getRawDescription", isMetadata=True, storage=MetadataStorage(), generateMode="mVc", validators=('isTidyHtmlWithCleanup', ), default_output_type='text/x-html-safe', allowable_content_type=('text/html', 'text/x-html-safe'), schemata='default', widget=RichWidget( label=_(u'label_description', default=u'Description'), description=_(u'help_description', default=u'A short summary of the content.'), rows=25, allow_file_upload=zconf.ATDocument.allow_document_upload) ) del ATNewsItemSchema['description'] ATNewsItemSchema.addField(description) ATNewsItemSchema.moveField('description', after='title') finalizeATCTSchema(ATNewsItemSchema)
REQUEST = context.REQUEST old_id = context.getId() try: new_context = context.portal_factory.doCreate(context, id) except AttributeError: # Fallback for AT + plain CMF where we don't have a portal_factory new_context = context new_context.processForm() # Get the current language and put it in request/LANGUAGE form = REQUEST.form if 'current_lang' in form: form['language'] = form.get('current_lang') portal_status_message = _(u'Changes saved.') # handle navigation for multi-page edit forms next = not REQUEST.get('form.button.next', None) is None previous = not REQUEST.get('form.button.previous', None) is None fieldset = REQUEST.get('fieldset', None) schemata = new_context.Schemata() if next or previous: s_names = [s for s in schemata.keys() if s != 'metadata'] if previous: s_names.reverse() next_schemata = None try:
from Products.CMFCore import permissions, utils from AccessControl import ClassSecurityInfo from App.class_init import InitializeClass from Acquisition import aq_base from Acquisition import aq_inner from ExtensionClass import Base from zope.interface import implements TemplateMixinSchema = Schema(( # TemplateMixin StringField('layout', write_permission=permissions.ModifyPortalContent, default_method="getDefaultLayout", vocabulary="_voc_templates", widget=SelectionWidget(label=_(u'label_template_mixin', default=u'View template'), description=_(u'help_template_mixin', default=u'Choose a template that will be used for viewing this item.'), visible={'view': 'hidden', 'edit': 'visible'},) ), )) class TemplateMixin(Base): implements(ITemplateMixin) schema = TemplateMixinSchema actions = ( {'id': 'view',
from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes.atapi import * class DummyDiscussionTool: def isDiscussionAllowedFor(self, content): return False def overrideDiscussionFor(self, content, allowDiscussion): pass MULTIPLEFIELD_LIST = DisplayList( ( ("1", _(u"Option 1 : printemps")), ("2", unicode("Option 2 : \xc3\xa9t\xc3\xa9", "utf-8")), # e-acute t e-acute ("3", u"Option 3 : automne"), ("4", _(u"option3", default=u"Option 3 : hiver")), ) ) schema = BaseSchema + Schema( ( LinesField( "MULTIPLEFIELD", searchable=1, vocabulary=MULTIPLEFIELD_LIST, widget=MultiSelectionWidget(i18n_domain="plone"), ), TextField("TEXTFIELD", primary=True),
def _Vocabulary(self, content_instance): """overload Archetypes Products.Archetypes.Field.ReferenceField._Vocabulary to make a restriction on the _path_ for performance gain """ pairs = [] pc = getToolByName(content_instance, 'portal_catalog') uc = getToolByName(content_instance, config.UID_CATALOG) purl = getToolByName(content_instance, 'portal_url') allowed_types = self.allowed_types allowed_types_method = getattr(self, 'allowed_types_method', None) if allowed_types_method: meth = getattr(content_instance,allowed_types_method) allowed_types = meth(self) skw = allowed_types and {'portal_type':allowed_types} or {} brains = uc.searchResults(skw) if self.vocabulary_custom_label is not None: label = lambda b:eval(self.vocabulary_custom_label, {'b': b}) elif self.vocabulary_display_path_bound != -1 and len(brains) > self.vocabulary_display_path_bound: at = _(u'label_at', default=u'at') label = lambda b:u'%s %s %s' % (self._brains_title_or_id(b, content_instance), at, b.getPath()) else: label = lambda b:self._brains_title_or_id(b, content_instance) # The UID catalog is the correct catalog to pull this # information from, however the workflow and perms are not accounted # for there. We thus check each object in the portal catalog # to ensure it validity for this user. portal_base = purl.getPortalPath() path_offset = len(portal_base) + 1 abs_paths = {} abs_path = lambda b, p=portal_base: '%s/%s' % (p, b.getPath()) # modifications sd = (portal_base + "/" + self.widget.getStartupDirectory( content_instance, self)).replace('//', '/') for b in brains: apath = abs_path(b) if apath.startswith(sd): abs_paths.update({apath:b}) # end modifications pc_brains = pc(path=abs_paths.keys(), **skw) for b in pc_brains: b_path = b.getPath() # translate abs path to rel path since uid_cat stores # paths relative now path = b_path[path_offset:] # The reference field will not expose Refrerences by # default, this is a complex use-case and makes things too hard to # understand for normal users. Because of reference class # we don't know portal type but we can look for the annotation key in # the path if self.referenceReferences is False and \ path.find(config.REFERENCE_ANNOTATION) != -1: continue # now check if the results from the pc is the same as in uc. # so we verify that b is a result that was also returned by uc, # hence the check in abs_paths. if abs_paths.has_key(b_path): uid = abs_paths[b_path].UID if uid is None: # the brain doesn't have an uid because the catalog has a # staled object. THAT IS BAD! raise ReferenceException("Brain for the object at %s "\ "doesn't have an UID assigned with. Please update your"\ " reference catalog!" % b_path) pairs.append((uid, label(b))) if not self.required and not self.multiValued: no_reference = _(u'label_no_reference', default=u'<no reference>') pairs.insert(0, ('', no_reference)) __traceback_info__ = (content_instance, self.getName(), pairs) return DisplayList(pairs)
class ImportView(BrowserView): template = ViewPageTemplateFile('import.pt') def __call__(self): self.processed = False self.errors = {} start_time = self.context.ZopeTime().timeTime() if not self.request.form.get('form.submitted'): return self.template() # fetch value from request input_encoding = self.request.form.get('input_encoding', 'utf-8') span_of_search = self.request.form.get('span_of_search', None) format = self.request.form.get('format', 'bib') # process source filename = None source = self.request.form.get('up_text') if not source: upfile = self.request.form.get('file') filename = upfile and getattr(upfile, 'filename', None) if not filename: self.errors['file'] = _(u'You must import a file or enter a' ' text.') addStatusMessage(self.request, _(u"Please correct the indicated errors.")) return self.template() source = upfile.read() if not source or not isinstance(source, basestring): msg = "Could not read the file '%s'." % filename self.errors['file'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() # skip DOS line breaks source = source.replace('\r', '') # get parsed entries from the Bibliography Tool bibtool = getToolByName(self.context, 'portal_bibliography') try: entries = bibtool.getEntries(source, format, filename, input_encoding=input_encoding) except ImportParseError: msg = """%s Parser's 'checkFormat' and guessing the format""" \ """ from the file name '%s' failed.""" % (format, filename) self.errors['format'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except UnicodeError: msg = """The choosen input encoding does not match the real """ \ """encoding of your input data in order to convert it to """\ """unicode internally.""" self.errors['input_encoding'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except RuntimeError, e: addStatusMessage(self.request, _(unicode(e))) return self.template() # debug message if entries is not a python list if not entries or not isinstance(entries, (list, tuple)): msg = "There must be something wrong with the parser" addStatusMessage(self.request, _(unicode(msg))) return self.template() # start building the report mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() fullname = member.getProperty('fullname', None) if fullname: username = '******' % (_encode(fullname), _encode(member.getId())) else: username = _encode(member.getId()) tmp_report = '[%s] Imported by %s' % (self.context.ZopeTime(), username) if filename is not None: tmp_report += ' from file %s' % _encode(filename) tmp_report += ':\n\n' # process import for each entry processedEntries = 0 importErrors = 0 logger.info('Start import of %s raw entries.' % len(entries)) counter = 0 for entry in entries: counter += 1 count = '#%05i: ' % counter logger.info(count + 'processing entry') # Workaround for #36 where an entry represents # an error from parser instead of a dict containing # importable data if isinstance(entry, basestring): msg = 'Entry could not be parsed! %s' % _encode(entry) upload = (msg, 'error') logger.error(count + msg) elif entry.get('title'): logger.info(count + 'Normal processing') upload = self.context.processSingleImport( entry, span_of_search=span_of_search) else: formated = '; '.join([ '%s=%s' % (key, entry[key]) for key in sorted(entry.keys()) if key == key.lower() ]) upload = ('Found entry without title: %s\n' % formated, 'error') logger.error(count + upload[0]) if upload[1] == 'ok': processedEntries += 1 else: importErrors += 1 state, msg = _encode(upload[1].upper()), _encode(upload[0]) tmp_report += '%s: %s\n' % (state, msg) self.context.logImportReport(tmp_report) self.processed = True # set the portal status message up msg = "Processed %i entries. There were %i errors. "\ "Import processed in %f seconds. See import report below." \ % (processedEntries, importErrors, self.context.ZopeTime().timeTime() - start_time) logger.info(msg) addStatusMessage(self.request, _(unicode(msg))) return self.template()
def getWidgets(self, instance=None, package=None, type=None, context=None, mode='edit', fields=None, schemata=None, nosort=None): """Empty widgets for standalone rendering. """ widgets = [] w_keys = {} context = context is not None and context or self instances = instance is not None and [instance] or [] f_names = fields if not instances: for t in self.listTypes(package, type): instance = t('fake_instance') instance._at_is_fake_instance = True wrapped = instance.__of__(context) wrapped.initializeArchetype() instances.append(wrapped) for instance in instances: if schemata is not None: schema = instance.Schemata()[schemata].copy() else: schema = instance.Schema().copy() fields = schema.fields() if mode == 'search': # Include only fields which have an index # XXX duplicate fieldnames may break this, # as different widgets with the same name # on different schemas means only the first # one found will be used indexes = self.portal_catalog.indexes() fields = [f for f in fields if (f.accessor and not f.accessor in w_keys and f.accessor in indexes)] if f_names is not None: fields = filter(lambda f: f.getName() in f_names, fields) for field in fields: widget = field.widget field_name = field.getName() accessor = field.getAccessor(instance) if mode == 'search': field.required = False field.addable = False # for ReferenceField if not isinstance(field.vocabulary, DisplayList): field.vocabulary = field.Vocabulary(instance) if '' not in field.vocabulary.keys(): field.vocabulary = DisplayList([('', _(u'at_search_any', default=u'<any>'))]) + \ field.vocabulary widget.populate = False field_name = field.accessor # accessor must be a method which doesn't take an argument # this lambda is facking an accessor accessor = lambda: field.getDefault(instance) w_keys[field_name] = None widgets.append((field_name, WidgetWrapper( field_name=field_name, mode=mode, widget=widget, instance=instance, field=field, accessor=accessor))) if mode == 'search' and nosort == None: widgets.sort() return [widget for name, widget in widgets]
class ExtensibleMetadata(Persistence.Persistent): """ A DC metadata implementation for Plone Archetypes """ implements(IExtensibleMetadata) security = ClassSecurityInfo() schema = type = MetadataSchema(( BooleanField( 'allowDiscussion', accessor="isDiscussable", mutator="allowDiscussion", edit_accessor="editIsDiscussable", default=None, enforceVocabulary=1, widget=BooleanWidget( label=_(u'label_allow_comments', default=u'Allow comments'), description=_(u'help_allow_comments', default=u'If selected, users can add comments ' 'to this item.')), ), LinesField( 'subject', multiValued=1, accessor="Subject", searchable=True, widget=TagsWidget( label=_(u'label_tags', default=u'Tags'), description=_(u'help_tags', default=u'Tags are commonly used for ad-hoc ' 'organization of content.'), ), ), TextField( 'description', default='', searchable=1, accessor="Description", default_content_type='text/plain', allowable_content_types=('text/plain', ), widget=TextAreaWidget( label=_(u'label_description', default=u'Description'), description=_( u'help_description', default=u'Used in item listings and search results.'), ), ), # Location, also known as Coverage in the DC metadata standard, but we # keep the term Location here for historical reasons. StringField( 'location', # why no accessor? http://dev.plone.org/plone/ticket/6424 searchable=True, widget=StringWidget( label=_(u'label_location', default=u'Location'), description=_( u'help_location_dc', default= u'The geographical location associated with the item, if applicable.' ), ), ), LinesField( 'contributors', accessor="Contributors", widget=AjaxSelectWidget( label=_(u'label_contributors', u'Contributors'), description=_( u'help_contributors', default=u"The names of people that have contributed " "to this item. Each contributor should " "be on a separate line."), vocabulary="plone.app.vocabularies.Users"), ), LinesField( 'creators', accessor="Creators", widget=AjaxSelectWidget( label=_(u'label_creators', u'Creators'), description=_( u'help_creators', default=u"Persons responsible for creating the content of " "this item. Please enter a list of user names, one " "per line. The principal creator should come first."), vocabulary="plone.app.vocabularies.Users"), ), DateTimeField( 'effectiveDate', mutator='setEffectiveDate', languageIndependent=True, widget=DatetimeWidget( label=_(u'label_effective_date', u'Publishing Date'), description=_( u'help_effective_date', default=u"The date when the item will be published. If no " "date is selected the item will be published immediately." ), ), ), DateTimeField( 'expirationDate', mutator='setExpirationDate', languageIndependent=True, widget=DatetimeWidget( label=_(u'label_expiration_date', u'Expiration Date'), description=_( u'help_expiration_date', default= u"The date when the item expires. This will automatically " "make the item invisible for others at the given date. " "If no date is chosen, it will never expire."), ), ), StringField( 'language', accessor="Language", default=config.LANGUAGE_DEFAULT, default_method='defaultLanguage', vocabulary='languages', widget=SelectWidget(label=_(u'label_language', default=u'Language'), ), ), TextField( 'rights', accessor="Rights", default_method='defaultRights', allowable_content_types=('text/plain', ), widget=TextAreaWidget( label=_(u'label_copyrights', default=u'Rights'), description=_( u'help_copyrights', default= u'Copyright statement or other rights information on this item.' ), )), )) + Schema(( # XXX change this to MetadataSchema in AT 1.4 # Currently we want to stay backward compatible without migration # between beta versions so creation and modification date are using the # standard schema which leads to AttributeStorage DateTimeField( 'creation_date', accessor='created', mutator='setCreationDate', default_method=DateTime, languageIndependent=True, isMetadata=True, schemata='metadata', generateMode='mVc', widget=DatetimeWidget( label=_(u'label_creation_date', default=u'Creation Date'), description=_(u'help_creation_date', default=u'Date this object was created'), visible={ 'edit': 'invisible', 'view': 'invisible' }), ), DateTimeField( 'modification_date', accessor='modified', mutator='setModificationDate', default_method=DateTime, languageIndependent=True, isMetadata=True, schemata='metadata', generateMode='mVc', widget=DatetimeWidget( label=_(u'label_modification_date', default=u'Modification Date'), description=_(u'help_modification_date', default=u'Date this content was modified last'), visible={ 'edit': 'invisible', 'view': 'invisible' }), ), )) def __init__(self): pass security.declarePrivate('defaultLanguage') def defaultLanguage(self): """Retrieve the default language""" tool = getToolByName(self, 'portal_languages', None) if tool is not None: return tool.getDefaultLanguage() return config.LANGUAGE_DEFAULT security.declarePrivate('defaultRights') def defaultRights(self): """Retrieve the default rights""" mdtool = getToolByName(self, 'portal_metadata', None) if mdtool is None: return '' for sid, schema in mdtool.listSchemas(): if not hasattr(schema, 'listPolicies'): # Broken class from CMFDefault. continue for pid, policy in schema.listPolicies(typ=self.Type()): if pid != 'Rights' and not policy.supply_default: continue return policy.default_value return '' security.declareProtected(permissions.View, 'isDiscussable') def isDiscussable(self, encoding=None): log_deprecated( "The isDiscussable method from the ExtensibleMetadata in " "Products.ATContentTypes has been deprecated and will be removed " "in Plone 5. This method belongs to the old discussion " "infrastructure that already has been replaced by " "plone.app.discussion in Plone 4.1.") if not 'portal_discussion' in self.objectIds(): return # Returns either True or False dtool = getToolByName(self, 'portal_discussion') return dtool.isDiscussionAllowedFor(self) security.declareProtected(permissions.View, 'editIsDiscussable') def editIsDiscussable(self, encoding=None): log_deprecated( "The editIsDiscussable method from the ExtensibleMetadata in " "Products.ATContentTypes has been deprecated and will be removed " "in Plone 5. This method belongs to the old discussion " "infrastructure that already has been replaced by " "plone.app.discussion in Plone 4.1.") if not 'portal_discussion' in self.objectIds(): return # Returns True, False or if None the default value result = self.rawIsDiscussable() if result is not None: return result default = self.defaultIsDiscussable() return default security.declareProtected(permissions.View, 'rawIsDiscussable') def rawIsDiscussable(self): log_deprecated( "The rawIsDiscussable method from the ExtensibleMetadata in " "Products.ATContentTypes has been deprecated and will be removed " "in Plone 5. This method belongs to the old discussion " "infrastructure that already has been replaced by " "plone.app.discussion in Plone 4.1.") if not 'portal_discussion' in self.objectIds(): return # Returns True, False or None where None means use the default result = getattr(aq_base(self), 'allow_discussion', None) if result is not None: result = bool(result) return result security.declareProtected(permissions.View, 'defaultIsDiscussable') def defaultIsDiscussable(self): log_deprecated( "The defaultIsDiscussable method from the ExtensibleMetadata in " "Products.ATContentTypes has been deprecated and will be removed " "in Plone 5. This method belongs to the old discussion " "infrastructure that already has been replaced by " "plone.app.discussion in Plone 4.1.") if not 'portal_discussion' in self.objectIds(): return # Returns the default value, either True or False default = None typeInfo = self.getTypeInfo() if typeInfo: default = typeInfo.allowDiscussion() return default security.declareProtected(permissions.ModifyPortalContent, 'allowDiscussion') def allowDiscussion(self, allowDiscussion=None, **kw): pass # Vocabulary methods ###################################################### security.declareProtected(permissions.View, 'languages') def languages(self): """Vocabulary method for the language field """ util = None use_combined = False # Respect the combined language code setting from PloneLanguageTool lt = getToolByName(self, 'portal_languages', None) if lt is not None: use_combined = lt.use_combined_language_codes # Try the utility first if HAS_PLONE_I18N: util = queryUtility(IMetadataLanguageAvailability) # Fall back to acquiring availableLanguages if util is None: languages = getattr(self, 'availableLanguages', None) if callable(languages): languages = languages() # Fall back to static definition if languages is None: return DisplayList( (('en', 'English'), ('fr', 'French'), ('es', 'Spanish'), ('pt', 'Portuguese'), ('ru', 'Russian'))) else: languages = util.getLanguageListing(combined=use_combined) languages.sort(key=lambda x: x[1]) # Put language neutral at the top. languages.insert(0, (u'', _(u'Language neutral'))) return DisplayList(languages) # DublinCore interface query methods ##################################### security.declareProtected(permissions.View, 'CreationDate') def CreationDate(self, zone=None): """ Dublin Core element - date resource created. """ if zone is None: zone = _zone creation = self.getField('creation_date').get(self) # return unknown if never set properly return creation is None and 'Unknown' or creation.toZone( zone).ISO8601() security.declareProtected(permissions.View, 'EffectiveDate') def EffectiveDate(self, zone=None): """ Dublin Core element - date resource becomes effective. """ if zone is None: zone = _zone effective = self.getField('effectiveDate').get(self) return effective is None and 'None' or effective.toZone(zone).ISO8601() def _effective_date(self): """Computed attribute accessor """ return self.getField('effectiveDate').get(self) security.declareProtected(permissions.View, 'effective_date') effective_date = ComputedAttribute(_effective_date, 1) security.declareProtected(permissions.View, 'ExpirationDate') def ExpirationDate(self, zone=None): """Dublin Core element - date resource expires. """ if zone is None: zone = _zone expires = self.getField('expirationDate').get(self) return expires is None and 'None' or expires.toZone(zone).ISO8601() def _expiration_date(self): """Computed attribute accessor """ return self.getField('expirationDate').get(self) security.declareProtected(permissions.View, 'expiration_date') expiration_date = ComputedAttribute(_expiration_date, 1) security.declareProtected(permissions.View, 'Date') def Date(self, zone=None): """ Dublin Core element - default date """ # Return effective_date if specifically set, modification date # otherwise if zone is None: zone = _zone effective = self.getField('effectiveDate').get(self) if effective is None: effective = self.modified() return (effective is None and DateTime().toZone(zone) or effective.toZone(zone).ISO8601()) security.declareProtected(permissions.View, 'Format') def Format(self): """cmf/backward compat Dublin Core element - resource format """ # FIXME: get content type from marshaller return self.getContentType() security.declareProtected(permissions.ModifyPortalContent, 'setFormat') def setFormat(self, value): """cmf/backward compat: ignore setFormat""" self.setContentType(value) def Identifer(self): """ dublin core getId method""" return self.getId() # DublinCore utility methods ############################################# security.declareProtected(permissions.View, 'contentEffective') def contentEffective(self, date): """Is the date within the resource's effective range? """ effective = self.getField('effectiveDate').get(self) expires = self.getField('expirationDate').get(self) pastEffective = (effective is None or effective <= date) beforeExpiration = (expires is None or expires >= date) return pastEffective and beforeExpiration security.declareProtected(permissions.View, 'contentExpired') def contentExpired(self, date=None): """ Is the date after resource's expiration """ if not date: date = DateTime() expires = self.getField('expirationDate').get(self) if not expires: expires = CEILING_DATE return expires <= date # CatalogableDublinCore methods ########################################## security.declareProtected(permissions.View, 'created') def created(self): """Dublin Core element - date resource created, returned as DateTime. """ # allow for non-existent creation_date, existed always created = self.getField('creation_date').get(self) return created is None and FLOOR_DATE or created security.declareProtected(permissions.View, 'modified') def modified(self): """Dublin Core element - date resource last modified, returned as DateTime. """ modified = self.getField('modification_date').get(self) # TODO may return None return modified security.declareProtected(permissions.View, 'effective') def effective(self): """Dublin Core element - date resource becomes effective, returned as DateTime. """ effective = self.getField('effectiveDate').get(self) return effective is None and FLOOR_DATE or effective security.declareProtected(permissions.View, 'expires') def expires(self): """Dublin Core element - date resource expires, returned as DateTime. """ expires = self.getField('expirationDate').get(self) return expires is None and CEILING_DATE or expires ## code below come from CMFDefault.DublinCore.DefaultDublinCoreImpl ####### ########################################################################### # # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ########################################################################### # # Set-modification-date-related methods. # In DefaultDublinCoreImpl for lack of a better place. # security.declareProtected(permissions.ModifyPortalContent, 'notifyModified') def notifyModified(self): """ Take appropriate action after the resource has been modified. For now, change the modification_date. """ self.setModificationDate(DateTime()) if shasattr(self, 'http__refreshEtag'): self.http__refreshEtag() security.declareProtected(permissions.ManagePortal, 'setModificationDate') def setModificationDate(self, modification_date=None): """Set the date when the resource was last modified. When called without an argument, sets the date to now. """ if modification_date is None: modified = DateTime() else: modified = self._datify(modification_date) self.getField('modification_date').set(self, modified) security.declareProtected(permissions.ManagePortal, 'setCreationDate') def setCreationDate(self, creation_date=None): """Set the date when the resource was created. When called without an argument, sets the date to now. """ if creation_date is None: created = DateTime() else: created = self._datify(creation_date) self.getField('creation_date').set(self, created) security.declarePrivate('_datify') def _datify(self, date): """Try to convert something into a DateTime instance or None """ # stupid web if date == 'None': date = None if not isinstance(date, DateTime): if date is not None: date = DateTime(date) return date # # DublinCore interface query methods # security.declareProtected(permissions.View, 'Publisher') def Publisher(self): """Dublin Core element - resource publisher """ # XXX: fixme using 'portal_metadata' return 'No publisher' security.declareProtected(permissions.View, 'ModificationDate') def ModificationDate(self, zone=None): """ Dublin Core element - date resource last modified. """ if zone is None: zone = _zone modified = self.modified() return (modified is None and DateTime().toZone(zone) or modified.toZone(zone).ISO8601()) security.declareProtected(permissions.View, 'Type') def Type(self): """Dublin Core element - Object type""" if hasattr(aq_base(self), 'getTypeInfo'): ti = self.getTypeInfo() if ti is not None: return ti.Title() return self.meta_type security.declareProtected(permissions.View, 'Identifier') def Identifier(self): """Dublin Core element - Object ID""" # XXX: fixme using 'portal_metadata' (we need to prepend the # right prefix to self.getPhysicalPath(). return self.absolute_url() security.declareProtected(permissions.View, 'listContributors') def listContributors(self): """Dublin Core element - Contributors""" return self.Contributors() security.declareProtected(permissions.ModifyPortalContent, 'addCreator') def addCreator(self, creator=None): """ Add creator to Dublin Core creators. """ if creator is None: mtool = getToolByName(self, 'portal_membership', None) if mtool is None: return creator = mtool.getAuthenticatedMember().getId() # call self.listCreators() to make sure self.creators exists curr_creators = self.listCreators() if creator and not creator in curr_creators: self.setCreators(curr_creators + (creator, )) security.declareProtected(permissions.View, 'listCreators') def listCreators(self): """ List Dublin Core Creator elements - resource authors. """ creators = self.Schema()['creators'] if not creators.get(self): # for content created with CMF versions before 1.5 owner_tuple = self.getOwnerTuple() owner_id = owner_tuple and owner_tuple[1] if owner_id: creators.set(self, (owner_id, )) else: creators.set(self, ()) return creators.get(self) security.declareProtected(permissions.View, 'Creator') def Creator(self): """ Dublin Core Creator element - resource author. """ creators = self.listCreators() return creators and creators[0] or '' # # DublinCore utility methods # # Deliberately *not* protected by a security declaration # See https://dev.plone.org/archetypes/ticket/712 def content_type(self): """ WebDAV needs this to do the Right Thing (TM). """ return self.Format() # # CatalogableDublinCore methods # security.declareProtected(permissions.View, 'getMetadataHeaders') def getMetadataHeaders(self): """ Return RFC-822-style headers. """ hdrlist = [] hdrlist.append(('Title', self.Title())) hdrlist.append(('Subject', string.join(self.Subject(), ', '))) hdrlist.append(('Publisher', self.Publisher())) hdrlist.append(('Description', self.Description())) hdrlist.append(('Contributors', string.join(self.Contributors(), '; '))) hdrlist.append(('Creators', string.join(self.Creators(), '; '))) hdrlist.append(('Effective_date', self.EffectiveDate())) hdrlist.append(('Expiration_date', self.ExpirationDate())) hdrlist.append(('Type', self.Type())) hdrlist.append(('Format', self.Format())) hdrlist.append(('Language', self.Language())) hdrlist.append(('Rights', self.Rights())) return hdrlist # # Management tab methods # security.declarePrivate('_editMetadata') def _editMetadata( self, title=_marker, subject=_marker, description=_marker, contributors=_marker, effective_date=_marker, expiration_date=_marker, format=_marker, language=_marker, rights=_marker, ): """ Update the editable metadata for this resource. """ if title is not _marker: self.setTitle(title) if subject is not _marker: self.setSubject(subject) if description is not _marker: self.setDescription(description) if contributors is not _marker: self.setContributors(contributors) if effective_date is not _marker: self.setEffectiveDate(effective_date) if expiration_date is not _marker: self.setExpirationDate(expiration_date) if format is not _marker: self.setFormat(format) if language is not _marker: self.setLanguage(language) if rights is not _marker: self.setRights(rights) security.declareProtected(permissions.ModifyPortalContent, 'manage_metadata') manage_metadata = DTMLFile('zmi_metadata', config._www) security.declareProtected(permissions.ModifyPortalContent, 'manage_editMetadata') def manage_editMetadata( self, title, subject, description, contributors, effective_date, expiration_date, format, language, rights, REQUEST, ): """ Update metadata from the ZMI. """ self._editMetadata( title, subject, description, contributors, effective_date, expiration_date, format, language, rights, ) REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_metadata' + '?manage_tabs_message=Metadata+updated.') security.declareProtected(permissions.ModifyPortalContent, 'editMetadata') def editMetadata( self, title='', subject=(), description='', contributors=(), effective_date=None, expiration_date=None, format='text/html', language='en-US', rights='', ): """ used to be: editMetadata = WorkflowAction(_editMetadata) Need to add check for webDAV locked resource for TTW methods. """ self.failIfLocked() self._editMetadata( title=title, subject=subject, description=description, contributors=contributors, effective_date=effective_date, expiration_date=expiration_date, format=format, language=language, rights=rights, ) self.reindexObject()
def getWidgets(self, instance=None, package=None, type=None, context=None, mode='edit', fields=None, schemata=None, nosort=None): # Empty widgets for standalone rendering. widgets = [] w_keys = {} context = context is not None and context or self instances = instance is not None and [instance] or [] f_names = fields if not instances: for t in self.listTypes(package, type): instance = t('fake_instance') instance._at_is_fake_instance = True wrapped = instance.__of__(context) wrapped.initializeArchetype() instances.append(wrapped) for instance in instances: if schemata is not None: schema = instance.Schemata()[schemata].copy() else: schema = instance.Schema().copy() fields = schema.fields() if mode == 'search': # Include only fields which have an index # XXX duplicate fieldnames may break this, # as different widgets with the same name # on different schemas means only the first # one found will be used indexes = self.portal_catalog.indexes() fields = [ f for f in fields if (f.accessor and not f.accessor in w_keys and f.accessor in indexes) ] if f_names is not None: fields = filter(lambda f: f.getName() in f_names, fields) for field in fields: widget = field.widget field_name = field.getName() accessor = field.getAccessor(instance) if mode == 'search': field.required = False field.addable = False # for ReferenceField if not isinstance(field.vocabulary, DisplayList): field.vocabulary = field.Vocabulary(instance) if '' not in field.vocabulary.keys(): field.vocabulary = DisplayList([('', _(u'at_search_any', default=u'<any>'))]) + \ field.vocabulary widget.populate = False field_name = field.accessor # accessor must be a method which doesn't take an argument # this lambda is facking an accessor accessor = lambda: field.getDefault(instance) w_keys[field_name] = None widgets.append((field_name, WidgetWrapper(field_name=field_name, mode=mode, widget=widget, instance=instance, field=field, accessor=accessor))) if mode == 'search' and nosort == None: widgets.sort() return [widget for name, widget in widgets]
from App.class_init import InitializeClass from Acquisition import aq_base from Acquisition import aq_inner from ExtensionClass import Base from zope.interface import implements TemplateMixinSchema = Schema( ( # TemplateMixin StringField( "layout", write_permission=permissions.ModifyPortalContent, default_method="getDefaultLayout", vocabulary="_voc_templates", widget=SelectionWidget( label=_(u"label_template_mixin", default=u"View template"), description=_( u"help_template_mixin", default=u"Choose a template that will be used for viewing this item." ), visible={"view": "hidden", "edit": "visible"}, ), ), ) ) class TemplateMixin(Base): implements(ITemplateMixin) schema = TemplateMixinSchema
_marker = [] content_type = Schema( ( StringField( name="id", required=0, # Still actually required, but the widget will # supply the missing value on non-submits mode="rw", permission=permission_copy_or_move, accessor="getId", mutator="setId", default=None, widget=IdWidget( label=_(u"label_short_name", default=u"Short Name"), description=_( u"help_shortname", default=u"Should not contain spaces, underscores or mixed case. " "Short Name is part of the item's web address.", ), visible={"view": "invisible"}, ), ), StringField( name="title", required=1, searchable=1, default="", accessor="Title", widget=StringWidget(label_msgid="label_title", visible={"view": "invisible"}, i18n_domain="plone"),
def get_translated_validation_messages(self): context = aq_inner(self.context) request = context.REQUEST fieldnames = { 'organisation': translate(_('Company/Organisation')), 'address': translate(_('Address')), 'postal_code': translate(_('Postal Code')), 'city': translate(_('City')), 'country': translate(_('Country')), 'firstname': translate(_('Firstname')), 'lastname': translate(_('Lastname')), 'sector': translate(_('Sector')), 'email': translate(_('Email')), 'telephone': translate(_('Telephone')), } lang = context.portal_languages.getPreferredLanguage() messages = {} for field_id in fieldnames: fieldname = fieldnames[field_id] err_msgs = { 'required': translate( _(u'error_required', default=u'${name} is required, please correct.', mapping={'name': fieldname}), context=request, ), 'email': translate( _(u"You entered an invalid email address."), context=request, ), } messages[field_id] = err_msgs return {'messages': messages}
from Products.Archetypes import PloneMessageFactory as _ from Products.CMFCore.utils import getToolByName from Products.Archetypes.utils import DisplayList from Products.ATContentTypes.content import schemata from Products.ATContentTypes.content.schemata import marshall_register from Products.ATContentTypes.content.schemata import ATContentTypeSchema from Products.ATContentTypes.content.base import ATCTMixin from Products.ATContentTypes.content.document import ATDocument from Products.ATContentTypes.content.folder import ATFolder, ATBTreeFolder from Products.ATContentTypes.content.image import ATImage from Products.ATContentTypes.content.event import ATEvent from Products.ATContentTypes.content.file import ATFile from Products.ATContentTypes.content.newsitem import ATNewsItem new_subject_widget = AutocompleteWidget( label=_(u'label_categories', default = u'Categories'), description=_(u'help_categories', default = u'Also known as keywords, tags or labels, ' 'these help you categorize your content.'), actb_filter_bogus = 0, actb_expand_onfocus = 0, maxlength='1024' ) def getKeywords(self): portal_catalog = getToolByName(self, 'portal_catalog') res = portal_catalog.uniqueValuesFor('Subject') return DisplayList(zip(res,res)) ATCTMixin.getKeywords = getKeywords
_marker = [] content_type = Schema(( StringField( name='id', required=0, # Still actually required, but the widget will # supply the missing value on non-submits mode='rw', permission=permission_copy_or_move, accessor='getId', mutator='setId', default=None, widget=IdWidget( label=_(u'label_short_name', default=u'Short Name'), description=_(u'help_shortname', default=u'Should not contain spaces, underscores or mixed case. ' 'Short Name is part of the item\'s web address.'), visible={'view' : 'invisible'} ), ), StringField( name='title', required=1, searchable=1, default='', accessor='Title', widget=StringWidget( label_msgid='label_title',
REQUEST = context.REQUEST old_id = context.getId() try: new_context = context.portal_factory.doCreate(context, id) except AttributeError: # Fallback for AT + plain CMF where we don't have a portal_factory new_context = context new_context.processForm() # Get the current language and put it in request/LANGUAGE form = REQUEST.form if form.has_key('current_lang'): form['language'] = form.get('current_lang') portal_status_message = _(u'Changes saved.') # handle navigation for multi-page edit forms next = not REQUEST.get('form.button.next', None) is None previous = not REQUEST.get('form.button.previous', None) is None fieldset = REQUEST.get('fieldset', None) schemata = new_context.Schemata() if next or previous: s_names = [s for s in schemata.keys() if s != 'metadata'] if previous: s_names.reverse() next_schemata = None try: