def register(): """ Register fields """ registerField( EEAReferenceField, title="EEA Reference Field", description=("EEA Reference field that knows about is_required_for."))
def register(): """ Register fields """ registerField( EEAReferenceField, title="EEA Reference Field", description=("EEA Reference field that knows about is_required_for."), )
from Products.Archetypes.Field import ObjectField, Field from Products.Archetypes.Registry import registerField class LocationAreaField(ObjectField): """A field that stores strings""" _properties = Field._properties.copy() _properties.update({ 'type' : 'string', 'default': '', }) registerField(LocationAreaField, title='String', description='Used for storing simple strings')
rd[uid] = o # singlevalued ref fields return only the object, not a list, # unless explicitely specified by the aslist option if not self.multiValued: if len(rd) > 1: log("%s references for non multivalued field %s of %s" % (len(rd), self.getName(), instance)) if not aslist: if rd: rd = [rd[uid] for uid in rd.keys()][0] else: rd = None if not self.referencesSortable or not hasattr( aq_base(instance), 'at_ordered_refs'): if isinstance(rd, dict): return [rd[uid] for uid in rd.keys()] else: return rd refs = instance.at_ordered_refs order = refs[self.relationship] return [rd[uid] for uid in order if uid in rd.keys()] registerField(HistoryAwareReferenceField, title = "History Aware Reference", description = "", )
""" # Resolve items to guarantee all them have the key uid value = super(ResultsRangesField, self)._to_dict(value) return map(self.resolve_uid, value) def resolve_uid(self, raw_dict): """Returns a copy of the raw dictionary passed in, but with additional key "uid". It's value is inferred from "keyword" if present """ value = raw_dict.copy() uid = value.get("uid") if api.is_uid(uid) and uid != "0": return value # uid key does not exist or is not valid, try to infere from keyword keyword = value.get("keyword") if keyword: query = dict(portal_type="AnalysisService", getKeyword=keyword) brains = api.search(query, SETUP_CATALOG) if len(brains) == 1: uid = api.get_uid(brains[0]) value["uid"] = uid return value registerField( ResultsRangesField, title="ResultsRanges", description="Used for storing a results ranges", )
'value': _('Default value'), 'unit': _('Unit'), 'hidden': _('Hidden Field'), 'wide': _('Apply wide'), }, 'subfield_types': { 'hidden': 'boolean', 'value': 'float', 'wide': 'boolean', }, 'subfield_sizes': { 'keyword': 20, 'title': 20, 'value': 10, 'unit': 10, }, 'subfield_validators': { 'keyword': 'interimfieldsvalidator', 'title': 'interimfieldsvalidator', 'value': 'interimfieldsvalidator', 'unit': 'interimfieldsvalidator', }, }) security = ClassSecurityInfo() registerField( InterimFieldsField, title="Interim Fields", description="Used for storing Interim Fields or Interim Results.")
from Products.ATExtensions.ateapi import RecordField, RecordsField from Products.Archetypes.Registry import registerField from Products.Archetypes.public import * from Products.CMFCore.utils import getToolByName from Products.validation import validation from Products.validation.validators.RegexValidator import RegexValidator import sys from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t class ReferenceResultsField(RecordsField): """a list of reference sample results """ _properties = RecordsField._properties.copy() _properties.update({ 'type': 'referenceresult', 'subfields': ('uid', 'result', 'min', 'max', 'error'), 'subfield_labels': {'uid': _('Analysis Service'), 'result': _('Expected Result'), 'error': _('Permitted Error %'), 'min': _('Min'), 'max': _('Max')}, }) security = ClassSecurityInfo() registerField(ReferenceResultsField, title="Reference Values", description="Used for storing reference results", )
from App.class_init import InitializeClass from AccessControl import ClassSecurityInfo from Products.Archetypes.Field import StringField from Products.Archetypes.Registry import registerField from Products.ATExtensions.widget import EmailWidget class EmailField(StringField): """specific field for emails""" _properties = StringField._properties.copy() _properties.update({ 'type': 'email', 'validators': ('isEmail'), 'widget': EmailWidget, }) security = ClassSecurityInfo() InitializeClass(EmailField) registerField( EmailField, title="Email", description="Used for storing a validated email.", )
'type': 'FixedPoint', 'widget': DecimalWidget, 'validators': ('isDecimal'), }) security = ClassSecurityInfo() security.declarePrivate('set') def set(self, instance, value, **kwargs): """ Check if value is an actual FixedPoint value. If not, attempt to convert it to one; Raise an error if value is a float. Assign all properties passed as kwargs to object. field.set( FixedPoint(10)) field.set( FixedPointInstance) """ assert type(value) != type(0.00) if not value is None and not isinstance(value, FixedPoint): value = FixedPoint(value) ObjectField.set(self, instance, value, **kwargs) registerField(FixedPointField, title='FixedPoint', description=('Used for storing FixedPoint'))
# Return None if we could not find a proxied object, e.g. through # the proxy expression 'context.getSample()' on an AR if not proxy_object: logger.debug( "Expression '{}' did not return a valid Proxy Object on {}". format(self.proxy, instance)) return None # Lookup the proxied field by name field_name = self.getName() field = proxy_object.getField(field_name) # Bail out if the proxy object has no identical named field. if field is None: raise KeyError( "Object '{}' with id '{}' has no field named '{}'".format( proxy_object.portal_type, proxy_object.getId(), field_name)) # set the value on the proxy object field.set(proxy_object, value, **kwargs) # Register the field registerField( ProxyField, title='Proxy', description=( 'Used to proxy a value to a similar field on another object.'))
def validate(self, value, instance, errors=None, REQUEST=None, **kwargs): if not value.get('token'): return 'A payment has not been processed.' else: if not value.get('charge_data'): return 'Error calling stripe api' data = value['charge_data'] if 'error' in data: return 'Stripe API Error: %s' % data['error']['message'] # if we get this far, we need to cache the data to the request # for easy retrieval later... Sigh, yah, weird here... REQUEST.environ['%s-stripe' % self.getName()] = value return None registerField(StripeField, title='Stripe Field') class FGStripeField(FGStringField): """ A string entry field """ implements(IStripeField) security = ClassSecurityInfo() schema = FGStringField.schema.copy() + Schema(( LinesField( 'amounts', required=False, accessor="getAmounts", mutator="setAmounts",
filename = filename[max( filename.rfind('/'), filename.rfind('\\'), filename.rfind(':'), ) + 1:] if mimetype is None or mimetype == 'text/x-unknown-content-type': if body is None: body = value[:CHUNK] mtr = getToolByName(instance, 'mimetypes_registry', None) if mtr is not None: kw = {'mimetype': None, 'filename': filename} d, f, mimetype = mtr(body, **kw) else: mimetype, enc = guess_content_type(filename, body, mimetype) # mimetype, if coming from request can be like: # text/plain; charset='utf-8' #mimetype = str(mimetype).split(';')[0] mimetype = 'text/plain' file.update(value, instance, mimetype=mimetype, filename=filename) file.setContentType(instance, mimetype) file.setFilename(filename) return file, str(file.getContentType()), file.getFilename() registerField(PlainTextField, title='PlainTextField', description='A specialized field for plain text only')
def getAnswerSet(self): return self.answerSet def validate_required(self, instance, value, errors): for index in range(self.questionSet): if not value[index]: label = self.widget.Label(instance) name = self.getName() error = 'Answers to all questions of %s are required, please correct' % label errors[name] = error return error return None def validate(self, value, instance, errors=None, **kwargs): error = _('pfg_allRequired', 'An answer is required for each question.') if not self.required: return None for index in range(len(self.questionSet)): if (index > len(value)) or not value[index]: fname = self.getName() if fname not in errors: errors[fname] = error return error return None registerField(LikertField, title='Likert Field', description='Used for collecting Likert survey answers')
# if ResultsRangeDict is removed or changed value = dict(value) super(ResultRangeField, self).set(instance, value, **kwargs) def get(self, instance, **kwargs): from bika.lims.content.analysisspec import ResultsRangeDict value = super(ResultRangeField, self).get(instance, **kwargs) if value: return ResultsRangeDict(dict(value.items())) return {} registerField( ResultRangeField, title="ResultRange", description="Used for storing a result range", ) class DefaultResultsRangeProvider(object): """Default Results Range provider for analyses This is used for backwards-compatibility for when the analysis' ResultsRange was obtained directly from Sample's ResultsRanges field, before this: https://github.com/senaite/senaite.core/pull/1506 """ implements(IFieldDefaultProvider) def __init__(self, context): self.context = context
__docformat__ = 'restructuredtext' # Zope imports from AccessControl import ClassSecurityInfo from zope.interface import implements # Archetypes imports from Products.Archetypes.Registry import registerField # Products imports from Products.PloneArticle.field import BaseInnerContentField from Products.PloneArticle.interfaces import IImageInnerContentField class ImageInnerContentField(BaseInnerContentField): """""" implements(IImageInnerContentField) _properties = BaseInnerContentField._properties.copy() _properties.update({ 'inner_portal_type': 'ImageInnerContentProxy', 'is_folderish': True, }) security = ClassSecurityInfo() registerField(ImageInnerContentField, title='ImageInnerContent', description=('Used to store ImageInnerContentProxy objects.'))
inner_content = inner_klass(inner_content_id) inner_content._at_is_fake_instance = True inner_content._is_fake_instance = True wrapped = inner_content.__of__(instance) wrapped.initializeArchetype() return wrapped security.declarePrivate('getIndexableValue') def getIndexableValue(self, instance): """ Returns string value used on SearchableText index """ proxies = self.get(instance) return " ".join([x.SearchableText() for x in proxies]) security.declarePublic('writeable') def writeable(self, instance, debug=False): """Overriding standard Field.writeable such this field is not writeable on temporary objects (using portal_factory)""" if instance.isTemporary(): return False return super(BaseInnerContentField, self).writeable(instance, debug) registerField(BaseInnerContentField, title='BaseInnerContent', description=('Used to store objects implementing IBaseInnerContent.') )
'type': 'formattable_name', 'default': FormattableName(), 'subfields': ( 'title', 'firstname', 'middlename', 'lastname', ), 'widget': FormattableNameWidget, }) security = ClassSecurityInfo() security.declarePrivate('set') def set(self, instance, value, **kwargs): value = self._decode_strings(value, instance, **kwargs) value = FormattableName(value) ObjectField.set(self, instance, value, **kwargs) InitializeClass(FormattableNameField) registerField( FormattableNameField, title="Formattable Name", description="Used for storing a formattable name", )
}) security = ClassSecurityInfo() schema=schema security.declarePrivate('set') security.declarePrivate('get') def getRaw(self, instance, **kwargs): return CompoundField.getRaw(self, instance, **kwargs) def set(self, instance, value, **kwargs): return CompoundField.set(self, instance, value, **kwargs) def get(self, instance, **kwargs): return CompoundField.get(self, instance, **kwargs) registerField(TemporalAttestation, title='TemporalAttestation', description='') ##code-section module-footer #fill in your manual code here ##/code-section module-footer
ClassGen.generateMethods(instance.__class__, self.Schema()) self.already_bootstrapped = True return ObjectField.getAccessor(self, instance) def valueClass2Raw(self,value): res = dict() for k in value.__dict__: res[k]=(getattr(value, k),) return res def getFields(self,): return self.Schema().fields() def getField(self, key): """ get subfield of @param key""" return self.Schema().get(key) def __init__(self, name=None, schema=None, **kwargs): ObjectField.__init__(self, name, **kwargs) if not schema: schema = self.schema.copy() self.setSchema(schema) registerField(CompoundField, title='CompoundField', description='') ##code-section module-footer #fill in your manual code here ##/code-section module-footer
'type' : 'FixedPoint', 'widget' : DecimalWidget, 'validators' : ('isDecimal'), }) security = ClassSecurityInfo() security.declarePrivate('set') def set(self, instance, value, **kwargs): """ Check if value is an actual FixedPoint value. If not, attempt to convert it to one; Raise an error if value is a float. Assign all properties passed as kwargs to object. field.set( FixedPoint(10)) field.set( FixedPointInstance) """ assert type(value) != type(0.00) if not value is None and not isinstance(value, FixedPoint): value = FixedPoint(value) ObjectField.set(self, instance, value, **kwargs) registerField(FixedPointField, title='FixedPoint', description=('Used for storing FixedPoint'))
from App.class_init import InitializeClass from AccessControl import ClassSecurityInfo from Products.Archetypes.Field import StringField from Products.Archetypes.Registry import registerField from Products.ATExtensions.widget import EmailWidget class EmailField(StringField): """specific field for emails""" _properties = StringField._properties.copy() _properties.update({"type": "email", "validators": ("isEmail"), "widget": EmailWidget}) security = ClassSecurityInfo() InitializeClass(EmailField) registerField(EmailField, title="Email", description="Used for storing a validated email.")
the i18n translation values for date formats. This does not specifically check the date_format_short_datepicker, so this means that date_formats should be identical between the python strftime and the jquery version. """ _properties = Field._properties.copy() _properties.update({ 'type': 'datetime', 'widget': CalendarWidget, }) implements(IDateTimeField) security = ClassSecurityInfo() security.declarePrivate('set') def set(self, instance, value, **kwargs): """ Check if value is an actual date/time value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. """ val = get_date(instance, value) super(DateTimeField, self).set(instance, val, **kwargs) registerField(DateTimeField, title='Date Time', description='Used for storing date/time')
True) update_excluded = len(new_excluded) != 0 # remove old refs if they have been unchecked in widget for uid in new_excluded.iterkeys(): if old_value.has_key(uid): del old_value[uid] excluded_uids.update(new_excluded) # compute new value ensuring unique items in list value = dict.fromkeys(value) value.update(old_value) value = value.keys() # remove old excluded_uids if they have been checked in widget for k in excluded_uids.keys(): if k in value: del excluded_uids[k] update_excluded = (update_excluded or (len(excluded_uids) != old_excluded_count)) # write excluded uids only if it has changed if update_excluded: self.setExcludedUIDs(instance, excluded_uids) ReferenceField.set(self, instance, value, **kwargs) registerField(SmartListField, title="SmartListField", description=SmartListField.__doc__)
__traceback_info__ = (content_instance, self.getName(), pairs) return DisplayList(pairs) def getStartupDirectory(self, instance): storage = getUtility(IMarscatsSettingsStorage) portal_type = instance.portal_type name = self.getName() return storage.getStartupDir(name, portal_type, ispath=True) def get(self, instance, **kwargs): startup_directory = self.getStartupDirectory(instance) portal_url = getToolByName(instance, 'portal_url') portal = portal_url.getPortalObject() startup_folder = portal.restrictedTraverse(str(startup_directory)) startup_folder_url = startup_folder.absolute_url() refcat = getToolByName(instance, 'reference_catalog') items = [] kwargs['aslist'] = True value = ReferenceField.getRaw(self, instance, **kwargs) for uid in value: obj = refcat.lookupObject(uid) item = getTitledPath(obj, startup_folder_url) items.append(' / '.join(item)) return items registerField(MarscatField, title='Mars Categories', description=('Used for categorizing MARS Collection Objects.')) registerPropertyType('categories', 'tuple', MarscatField)
items = [(c.UID, c.title) for c in bsc(portal_type='Preservation', inactive_state='active', sort_on='sortable_title')] items = [['', _('Any')]] + list(items) return DisplayList(items) security.declarePublic('Containers') def Containers(self, instance=None): instance = instance or self items = getContainers(instance, allow_blank=True) return DisplayList(items) registerField(PartitionSetupField, title="", description="") # # XXX When you modify this schema, be sure to edit the list of fields ## to duplicate, in bika_analysisservices.py. schema = BikaSchema.copy() + Schema(( StringField('ShortTitle', schemata="Description", widget=StringWidget( label=_("Short title"), description=_( "If text is entered here, it is used instead of the " "title when the service is listed in column headings. " "HTML formatting is allowed.") ), ),
"""reset volatile stuff (indexation, preview) """ name = self.getName() setattr(instance, _preview_ % name, None) setattr(instance, _indexed_ % name, None) setattr(instance, _ispreview_ % name, None) setattr(instance, _isindexed_ % name, None) setattr(instance, _icon_ % name, None) setattr(instance, _smallicon_ % name, None) delattr(instance, _isindexed_ % name) delattr(instance, _ispreview_ % name) def _logException(self, instance): if instance and hasattr(instance, 'getPhysicalPath'): path = '/'.join(instance.getPhysicalPath()) filename = self.getFilename(instance) msg = 'EXCEPTION object: %s, file: %s: \n' % (path, filename) LOG.warning(msg, exc_info=True) else: LOG.warning('Exception occured', exc_info=True) InitializeClass(AttachmentField) from Products.Archetypes.Registry import registerField registerField( AttachmentField, title='Attachment', description='Used for storing files with advanced features.', )
}) security = ClassSecurityInfo() schema=schema security.declarePrivate('set') security.declarePrivate('get') def getRaw(self, instance, **kwargs): return CompoundField.getRaw(self,instance,**kwargs) def set(self, instance, value, **kwargs): return CompoundField.set(self,instance,value,**kwargs) def get(self, instance, **kwargs): return CompoundField.get(self,instance,**kwargs) registerField(XBoxField, title='XBoxField', description='') ##code-section module-footer #fill in your manual code here ##/code-section module-footer
delete_ids.append(analysis.getId()) if delete_ids: # Note: subscriber might promote the AR instance.manage_delObjects(ids = delete_ids) return new_analyses security.declarePublic('Vocabulary') def Vocabulary(self, content_instance = None): """ Create a vocabulary from analysis services """ vocab = [] for service in self.Services(): vocab.append((service.UID(), service.Title())) return vocab security.declarePublic('Services') def Services(self): """ Return analysis services """ bsc = getToolByName(self.context, 'bika_setup_catalog') if not shasattr(self, '_v_services'): self._v_services = [service.getObject() \ for service in bsc(portal_type = 'AnalysisService')] return self._v_services registerField(ARAnalysesField, title = 'Analyses', description = ('Used for Analysis instances') )
'type': 'angle', 'subfields': ('degrees', 'minutes', 'seconds', 'bearing'), ## 'required_subfields' : ('degrees', 'minutes', 'seconds', 'bearing'), 'subfield_labels': { 'degrees': _('Degrees'), 'minutes': _('Minutes'), 'seconds': _('Seconds'), 'bearing': _('Bearing') }, 'subfield_sizes': { 'degrees': 3, 'minutes': 2, 'seconds': 2, 'bearing': 1 }, 'subfield_validators': { 'degrees': 'coordinatevalidator', 'minutes': 'coordinatevalidator', 'seconds': 'coordinatevalidator', 'bearing': 'coordinatevalidator', }, }) registerField( CoordinateField, title="Coordinate", description="Used for storing coordinates", )
# # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright 2018-2019 by it's authors. # Some rights reserved, see README and LICENSE. from Products.Archetypes.Registry import registerField from Products.ATExtensions.ateapi import RecordField class AddressField(RecordField): """ dedicated address field""" _properties = RecordField._properties.copy() _properties.update({ 'type': 'address', 'subfields': ('address', 'city', 'zip', 'state', 'district', 'country'), 'outerJoin': '<br />', }) registerField( AddressField, title="Address", description="Used for storing address information", )
return blob.getContentType() else: return 'application/octet-stream' @security.private def getFilename(self, instance, fromBaseUnit=True): """ return the file name associated with the blob data """ blob = self.getUnwrapped(instance) if blob is not None: return blob.getFilename() else: return None registerField(BlobField, title='Blob', description='Used for storing files in blobs') # convenience base classes for blob-aware file & image fields class FileField(BlobField): """ base class for a blob-based file field """ _properties = BlobField._properties.copy() _properties.update({ 'type': 'file', }) registerField(FileField,
def validate(self, value, instance, errors=None, REQUEST=None, **kwargs): if not value.get('token'): return 'A payment has not been processed.' else: if not value.get('charge_data'): return 'Error calling stripe api' data = value['charge_data'] if 'error' in data: return 'Stripe API Error: %s' % data['error']['message'] # if we get this far, we need to cache the data to the request # for easy retrieval later... Sigh, yah, weird here... REQUEST.environ['%s-stripe' % self.getName()] = value return None registerField(StripeField, title='Stripe Field') class FGStripeField(FGStringField): """ A string entry field """ implements(IStripeField) security = ClassSecurityInfo() schema = FGStringField.schema.copy() + Schema( (LinesField( 'amounts', required=False, accessor="getAmounts", mutator="setAmounts",
items = [(c.UID, c.title) for c in bsc(portal_type='Preservation', inactive_state='active', sort_on='sortable_title')] items = [['', _('Any')]] + list(items) return DisplayList(items) security.declarePublic('Containers') def Containers(self, instance=None): instance = instance or self items = getContainers(instance, allow_blank=True) return DisplayList(items) registerField(PartitionSetupField, title="", description="") # # XXX When you modify this schema, be sure to edit the list of fields ## to duplicate, in bika_analysisservices.py. schema = BikaSchema.copy() + Schema(( StringField('ShortTitle', schemata="Description", widget=StringWidget( label=_("Short title"), description=_( "If text is entered here, it is used instead of the " "title when the service is listed in column headings. " "HTML formatting is allowed.") ), ),
""" __docformat__ = 'restructuredtext' # Zope imports from AccessControl import ClassSecurityInfo from zope.interface import implements # Archetypes imports from Products.Archetypes.Registry import registerField # Products imports from Products.PloneArticle.field import BaseInnerContentField from Products.PloneArticle.interfaces import ILinkInnerContentField class LinkInnerContentField(BaseInnerContentField): """""" implements(ILinkInnerContentField) _properties = BaseInnerContentField._properties.copy() _properties.update({ 'inner_portal_type': 'LinkInnerContentProxy', }) security = ClassSecurityInfo() registerField(LinkInnerContentField, title='LinkInnerContent', description=('Used to store LinkInnerContentProxy objects.'))
from bika.lims import bikaMessageFactory as _ class InterimFieldsField(RecordsField): """a list of InterimFields for calculations """ _properties = RecordsField._properties.copy() _properties.update({ 'type' : 'InterimFields', 'subfields' : ('keyword', 'title', 'value', 'unit', 'hidden'), 'required_subfields' : ('keyword', 'title'), 'subfield_labels' : {'keyword': _('Keyword'), 'title': _('Field Title'), 'value': _('Default value'), 'unit': _('Unit'), 'hidden': _('Hidden Field')}, 'subfield_types' : {'hidden': 'boolean', 'value': 'float'}, 'subfield_sizes' : {'keyword': 20, 'title': 20, 'value': 10, 'unit': 10}, 'subfield_validators' : {'keyword': 'interimfieldsvalidator', 'title': 'interimfieldsvalidator', 'value': 'interimfieldsvalidator', 'unit': 'interimfieldsvalidator'}, }) security = ClassSecurityInfo() registerField(InterimFieldsField, title = "Interim Fields", description = "Used for storing Interim Fields or Interim Results.", )
""" refs = self.get_versioned_references_for(instance) if not self.multiValued: if len(refs) > 1: logger.warning("Found {} references for non-multivalued " "reference field '{}' of {}".format( len(refs), self.getName(), repr(instance))) if not aslist: if refs: refs = refs[0] else: refs = None if not self.referencesSortable or not hasattr(aq_base(instance), "at_ordered_refs"): return refs refs = instance.at_ordered_refs order = refs[self.relationship] if order is None: return refs by_uid = dict(map(lambda ob: (api.get_uid(ob), ob), refs)) return [by_uid[uid] for uid in order if uid in by_uid] registerField(HistoryAwareReferenceField, title="History Aware Reference", description="")
if self.allowed_types: # we trust that all allowed_types are properly referencable and cataloged results = catalog(Type=self.allowed_types, path=ws_path) else: keys = catalog.uniqueValuesFor('UID') results = catalog(UID=keys, path=ws_path) #... but this should never happen results = [(r, r.getObject()) for r in results] value = [(r.UID, obj and (str(obj.Title().strip()) or \ str(obj.getId()).strip()) or \ log('Field %r: Object at %r could not be found' % \ (self.getName(), r.getURL())) or \ r.Title or r.UID) for r, obj in results] if not self.required: value.insert(0, ('', '<no reference>')) return DisplayList(value) try: from Products.Archetypes.Registry import registerField registerField(SortedLinesField, title='Sorted lines', description=('Used for storing a set of lines in sorted order',)) registerField(VersionField, title='Rhaptos Module Version', description=('Used for storing versions of modules.',)) registerField(WorkspaceReferenceField, title='Workspace Reference', description=('Used for storing references to Referencable Objects within a workspace',)) except ImportError: pass # we are probably in a < 1.2 version of Archetypes
"""field for holding a link to be displayed using a label""" _properties = RecordField._properties.copy() _properties.update({ 'type' : 'labeled_url', 'subfields' : ('label','url'), 'subfield_validators':{'url':'isURL'}, 'outerJoin':': ', 'widget' : LabeledUrlWidget, }) security = ClassSecurityInfo() InitializeClass(LabeledUrlField) registerField(SimpleNameField, title="SimpleName", description="Used for storing a structured (first, last) name", ) registerField(LocationField, title="Location", description="Used for storing a location (city, country)", ) registerField(AddressField, title="Address", description="Used for storing an address (street1, street2, zip, city, country)", ) registerField(ContactField, title="Contact", description="Used for storing contact information (name, phone, fax, email, address)",
registerWidget( OrderableReferenceWidget, title='Orderable Reference', used_for=('Products.OrderableReferenceField.OrderableReferenceField',) ) registerWidget( OrderableReferenceBrowserWidget, title='Orderable Reference Browser', used_for=('Products.OrderableReferenceField.OrderableReferenceField',) ) registerField( OrderableReferenceField, title="Orderable Reference Field", description=("Reference field that knows about an order of refs.") ) #addon for Relations try: from Products.Relations.field import RelationField except ImportError: class RelationField(atapi.ReferenceField): pass class OrderableRelationField(RelationField): _properties = RelationField._properties.copy() _properties.update({ 'multiValued': True,
""" Field """ from Products.Archetypes.Registry import registerField from eea.geotags.field.location import GeotagsStringField, GeotagsLinesField registerField(GeotagsStringField, title="Geotags String Field", description=("Geotags string field.")) registerField(GeotagsLinesField, title="Geotags Lines Field", description=("Geotags lines field."))
# -*- coding: utf-8 -*- # # Copyright 2018-2019 Botswana Harvard Partnership (BHP) from Products.Archetypes.Registry import registerField from bhp.lims import api from bika.lims.fields import ExtStringField class VolumeUnitField(ExtStringField): def set(self, instance, value, **kwargs): original = instance.__dict__.get(self.getName(), "") original_unit = api.get_unit(original) original_volume = api.get_leading_number(original) new_unit = api.get_unit(value, default=original_unit) new_vol = api.get_leading_number(value) or original_volume new_value = "{} {}".format(new_vol, new_unit) super(VolumeUnitField, self).set(instance, new_value, **kwargs) registerField( VolumeUnitField, title="VolumeUnit", description="Used for storing volume units", )
class ReportSerialTitleField(ExtensionField, ExtensionFieldMixin, SerialTitleField): """ Archetypes SchemaExtender aware serial title field """ class ReportManagementPlanField(ExtensionField, ExtensionFieldMixin, ManagementPlanField): """ Archetypes SchemaExtender aware management plan field """ class ReportFileField(ExtensionField, ExtensionFieldMixin, BlobField): """ Archetypes SchemaExtender aware file field """ def set(self, instance, value, **kwargs): """ Field mutator """ is_value = value and value != "DELETE_FILE" # Handle migration migration = kwargs.pop('_migration_', False) if is_value and not migration: notify(FileUploadedEvent(instance, value, True)) BlobField.set(self, instance, value, **kwargs) registerField(SerialTitleField, title='Serial Title Field', description=('Used for storing report serial title')) registerPropertyType('types_vocabulary', 'string') registerPropertyType('years_vocabulary', 'string')
class DurationField(RecordField): """ Stores duration in Days/Hours/Minutes """ security = ClassSecurityInfo() _properties = RecordField._properties.copy() _properties.update({ 'type': 'duration', 'subfields': ('days', 'hours', 'minutes'), 'subfield_labels': { 'days': _('Days'), 'hours': _('Hours'), 'minutes': _('Minutes') }, 'subfield_sizes': { 'days': 2, 'hours': 2, 'minutes': 2 }, 'subfield_validators': { 'days': 'duration_validator', 'hours': 'duration_validator', 'minutes': 'duration_validator' }, }) registerField( DurationField, title="Duration", description="Used for storing durations", )
_properties = RecordsField._properties.copy() _properties.update({ 'type' : 'formattable_names', 'default' : FormattableNames(), 'subfields' : ('title','firstname','middlename','lastname',), 'subfield_sizes' : {'title':10, 'firstname': 15, 'middlename':15, 'lastname':30}, 'widget' : FormattableNamesWidget, }) security = ClassSecurityInfo() security.declarePrivate('get') def get(self, instance, **kwargs): value = RecordsField.get(self, instance, **kwargs) return FormattableNames(value) security.declarePrivate('set') def set(self, instance, value, **kwargs): value = self._decode_strings(value, instance, **kwargs) value = FormattableNames(value) ObjectField.set(self, instance, value, **kwargs) InitializeClass(FormattableNamesField) registerField(FormattableNamesField, title="Formattable Names", description="Used for storing formattable names", )
if not isinstance(value, DTMLMethod): dtml = DTMLMethod(self.getName()) dtml.munge(value) value = dtml ObjectField.set(self, instance, value, **kwargs) def getDefault(self, instance): value = ObjectField.getDefault(self, instance) dtml = DTMLMethod(self.getName()) dtml.munge(value) return dtml.__of__(instance) registerField( DTMLField, title="DTML Field", description=("A field that stores and renders DTML Methods") ) class ZPTField(ObjectField): _properties = ObjectField._properties.copy() _properties.update({ 'type' : 'zpt', 'default': '<span tal:replace="here/title_or_id" />', 'default_content_type' : 'text/plain', 'required': True, 'widget': TextAreaWidget(visible={'view': 'invisible', 'edit': 'visible'}), 'validators': ('zptvalidator',)
'default_content_type' : 'text/plain', }) security = ClassSecurityInfo() security.declarePrivate('get') def get(self, instance, **kwargs): return ObjectField.get(self, instance, **kwargs) security.declarePrivate('getRaw') def getRaw(self, instance, **kwargs): return self.get(instance, **kwargs) security.declarePrivate('set') def set(self, instance, value, **kwargs): """Convert passed-in value to a float. If failure, set value to None.""" if value is not None: # should really blow if value is not valid __traceback_info__ = (self.getName(), instance, value, kwargs) value = (float(value[0]), float(value[1])) self.getStorage(instance).set(self.getName(), instance, value, **kwargs) registerField(LocationField, title="LocationField", description=("Field that can store coordinate information") )
title='CaptchaWidget', description=u'Renders a collective.recaptcha widget', used_for=('collective.atcaptchavalidation.Field.CaptchaField',) ) class CaptchaField(Field.ObjectField): """A field that stores strings""" _properties = Field.ObjectField._properties.copy() _properties.update({ 'type': 'captcha', 'required': True, 'widget': CaptchaWidget, }) security = ClassSecurityInfo() security.declarePrivate('get') def get(self, instance, **kwargs): pass security.declarePrivate('set') def set(self, instance, value, **kwargs): pass registerField(CaptchaField, title='Captcha', description='Used for form edit validation')
result = None for record in value: result = RecordField.validate(self, record, instance, errors={}, **kwargs) if result: return result return result InitializeClass(RecordsField) registerField( RecordsField, title="Records", description="Used for storing a list of records", ) registerPropertyType('subfields', 'lines', RecordsField) registerPropertyType('required_subfields', 'lines', RecordField) registerPropertyType('subfield_validators', 'mapping', RecordField) registerPropertyType('subfield_types', 'mapping', RecordsField) registerPropertyType('subfield_vocabularies', 'mapping', RecordsField) registerPropertyType('subfield_labels', 'mapping', RecordsField) registerPropertyType('subfield_sizes', 'mapping', RecordsField) registerPropertyType('subfield_maxlength', 'mapping', RecordsField) registerPropertyType('innerJoin', 'string', RecordsField) registerPropertyType('fixedSize', 'boolean', RecordsField) registerPropertyType('minimalSize', 'int', RecordsField) registerPropertyType('maximalSize', 'int', RecordsField)
self.watermark = read("logo.png") img = Image.open(self.watermark) # else: ## f_watermark = StringIO(cw) # img = cw # img = Image.open(self.watermark) mark= reduce_opacity(img,0.3,si) if self.watermark_position == 'bottom_right': position = (layer.size[0]-mark.size[0], layer.size[1]-mark.size[1]) layer.paste(mark, position) else: # TODO :: only supports bottom_right option till know. raise 'TODO :: only supports bottom_right option till know.' image = Image.composite(layer, image, layer) f_data = StringIO() image.save(f_data, 'jpeg') data = f_data.getvalue() f_image.close() f_data.close() # TODO add self.ZCacheable_invalidate() later self.createOriginal(instance, data, **kwargs) self.createScales(instance, value=data) registerField(WatermarkImageField, title='Watermark Image', description='A field that watermarks images.')
expr = ObjectField.get(self, instance, **kwargs) # Return the expression text return getattr(expr, 'text', expr) security.declarePrivate('set') def set(self, instance, value, **kwargs): if not isinstance(value, Expression.Expression): value = Expression.Expression(value) ObjectField.set(self, instance, value, **kwargs) def getDefault(self, instance): value = ObjectField.getDefault(self, instance) return Expression.Expression(value) registerField(TALESString, title='TALES String', description=('A field that can take a TALES expression ' 'and evaluate it.')) class TALESLines(ObjectField): _properties = ObjectField._properties.copy() _properties.update({ 'type': 'taleslines', 'default': ['python: True'], 'widget': LinesWidget, 'required': True, 'validators': ('talesvalidator',) }) security = ClassSecurityInfo()
# Convert UIDs to objects if api.is_uid(thing): thing = api.get_object_by_uid(thing, None) # Bail out if the thing is not a valid object if not api.is_object(thing): logger.warn("'{}' is not a valid object!".format(repr(thing))) return None # Ensure we have an object here and not a brain obj = api.get_object(thing) if IAnalysisService.providedBy(obj): return obj if IAnalysis.providedBy(obj): return obj.getAnalysisService() # An object, but neither an Analysis nor AnalysisService? # This should never happen. portal_type = api.get_portal_type(obj) logger.error("ARAnalysesField doesn't accept objects from {} type. " "The object will be dismissed.".format(portal_type)) return None registerField(ARAnalysesField, title="Analyses", description="Manages Analyses of ARs")
p1 = body.find(self._seperator) if p1 == -1: # no seperator: we return the whole body return body else: p1 = p1 + len(self._seperator) p2 = body.find(self._seperator, p1) return body[p1:p2] security.declarePrivate('set') def set(self, instance, value, **kwargs): if not isinstance(value, PythonScript): s = self._seperator body = "%s\n%s%s\n%s%s" % (self.header, s, value, s, self.footer) script = PythonScript(self.getName()) script.ZPythonScript_edit('**options', body) value = script ObjectField.set(self, instance, value, **kwargs) def getDefault(self, instance): value = ObjectField.getDefault(self, instance) script = PythonScript(self.getName()) script.ZPythonScript_edit('**options', value) return script.__of__(instance) registerField( PythonField, title="Python Field", description=("A field that stores Python Scripts") )
from Products.CMFCore.utils import getToolByName from Products.validation import validation from Products.validation.validators.RegexValidator import RegexValidator import sys from bika.lims import bikaMessageFactory as _ from bika.lims.utils import t class ReferenceResultsField(RecordsField): """a list of reference sample results """ _properties = RecordsField._properties.copy() _properties.update({ 'type': 'referenceresult', 'subfields': ('uid', 'result', 'min', 'max', 'error'), 'subfield_labels': { 'uid': _('Analysis Service'), 'result': _('Expected Result'), 'error': _('Permitted Error %'), 'min': _('Min'), 'max': _('Max') }, }) security = ClassSecurityInfo() registerField( ReferenceResultsField, title="Reference Values", description="Used for storing reference results", )
if blob is not None: return blob.getContentType() else: return 'application/octet-stream' security.declarePrivate('getFilename') def getFilename(self, instance, fromBaseUnit=True): """ return the file name associated with the blob data """ blob = self.getUnwrapped(instance) if blob is not None: return blob.getFilename() else: return None registerField(BlobField, title='Blob', description='Used for storing files in blobs') # convenience base classes for blob-aware file & image fields class FileField(BlobField): """ base class for a blob-based file field """ _properties = BlobField._properties.copy() _properties.update({ 'type': 'file', }) registerField(FileField, title='Blob-aware FileField',
ObjectField.set(self, instance, self.getRaw(instance), **kwargs) def _Vocabulary(self, content_instance): rel_vocab = utils.adddeleteVocab(content_instance, ruleset_ids=[self.relationship]) if rel_vocab: tuples = rel_vocab[0]['tuples'] else: tuples = [] brains = [t[0] for t in tuples] pairs = [(t[0].UID, t[0].Title) for t in tuples] if i18n and not self.required and not self.multiValued: no_reference = i18n.translate(domain='archetypes', msgid='label_no_reference', context=content_instance, default='<no reference>') pairs.insert(0, ('', no_reference)) __traceback_info__ = (content_instance, self.getName(), pairs) return DisplayList(pairs) registerField(RelationField, title='Relations', description='Used for storing references through Relations.')
from Products.Archetypes.Registry import registerField from Products.ATExtensions.ateapi import RecordField class AddressField(RecordField): """ dedicated address field""" _properties = RecordField._properties.copy() _properties.update({ 'type': 'address', 'subfields': ('address', 'city', 'zip', 'state', 'district', 'country'), 'outerJoin': '<br />', }) registerField(AddressField, title="Address", description="Used for storing address information", )
if not kwargs.has_key('lang'): kwargs['lang'] = self._getCurrentLanguage(instance) try: self.setLanguage(kwargs['lang']) image = super(BlobImageField, self).getScale(instance, scale, **kwargs) if not image or not image.get_size(): defaultLang = self.getDefaultLang(instance) if defaultLang: self.setLanguage(defaultLang) image = super(BlobImageField, self).getScale(instance, scale, **kwargs) return image finally: self.resetLanguage() registerField(BlobFileField, title='Multilanguage Blob File', description='Used for storing files in blobs') registerField(BlobImageField, title='Multilanguage Blob Image', description='Used for storing images in blobs') except ImportError: pass registerField(StringField, title='Multilanguage String', description='Used for storing simple strings') registerField(FileField, title='Multilanguage File', description='Used for storing files')
Defines LinkInnerContentField """ __docformat__ = 'restructuredtext' # Zope imports from AccessControl import ClassSecurityInfo from zope.interface import implements # Archetypes imports from Products.Archetypes.Registry import registerField # Products imports from Products.PloneArticle.field import BaseInnerContentField from Products.PloneArticle.interfaces import ILinkInnerContentField class LinkInnerContentField(BaseInnerContentField): """""" implements(ILinkInnerContentField) _properties = BaseInnerContentField._properties.copy() _properties.update({ 'inner_portal_type' : 'LinkInnerContentProxy', }) security = ClassSecurityInfo() registerField(LinkInnerContentField, title='LinkInnerContent', description=('Used to store LinkInnerContentProxy objects.') )