Back to index

plone3  3.1.7
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes
Archetypes.Field.Field Class Reference
Inheritance diagram for Archetypes.Field.Field:
Inheritance graph
[legend]
Collaboration diagram for Archetypes.Field.Field:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def copy
def __repr__
def validate
def validate_validators
def validate_required
def validate_vocabulary
def Vocabulary
def checkPermission
def writeable
def checkExternalEditor
def getWidgetName
def getName
def getType
def getDefault
def getAccessor
def getEditAccessor
def getMutator
def getIndexAccessor
def getIndexAccessorName
def toString
def isLanguageIndependent
def getI18nDomain

Public Attributes

 widget
 validators
 index_method

Static Public Attributes

tuple security = ClassSecurityInfo()

Private Member Functions

def _widgetLayer
def _validationLayer

Private Attributes

 __name__

Static Private Attributes

 __implements__ = IField,ILayerContainer
dictionary _properties

Detailed Description

Extend `DefaultLayerContainer`.
Implements `IField` and `ILayerContainer` interfaces.
Class security = public with default access = allow.
Class attribute _properties is a dictionary containing all of a
field's property values.

Definition at line 149 of file Field.py.


Constructor & Destructor Documentation

def Archetypes.Field.Field.__init__ (   self,
  name = None,
  kwargs 
)
Assign name to __name__. Add properties and passed-in
keyword args to __dict__. Validate assigned validator(s).

Reimplemented in Archetypes.Field.PhotoField.

Definition at line 197 of file Field.py.

00197 
00198     def __init__(self, name=None, **kwargs):
00199         """
00200         Assign name to __name__. Add properties and passed-in
00201         keyword args to __dict__. Validate assigned validator(s).
00202         """
00203         DefaultLayerContainer.__init__(self)
00204 
00205         if name is None:
00206             global _field_count
00207             _field_count += 1
00208             name = 'field.%s' % _field_count
00209 
00210         self.__name__ = name
00211 
00212         self.__dict__.update(self._properties)
00213         self.__dict__.update(kwargs)
00214 
00215         self._widgetLayer()
00216         self._validationLayer()
00217 
00218         self.registerLayer('storage', self.storage)

Here is the caller graph for this function:


Member Function Documentation

Return a string representation consisting of name, type and permissions.

Definition at line 236 of file Field.py.

00236 
00237     def __repr__(self):
00238         """
00239         Return a string representation consisting of name, type and permissions.
00240         """
00241         return "<Field %s(%s:%s)>" % (self.getName(), self.type, self.mode)

Here is the call graph for this function:

def Archetypes.Field.Field._validationLayer (   self) [private]
Resolve that each validator is in the service. If validator is
not, log a warning.

We could replace strings with class refs and keep things impl
the ivalidator in the list.

Note: this is not compat with aq_ things like scripts with __call__

Definition at line 252 of file Field.py.

00252 
00253     def _validationLayer(self):
00254         """
00255         Resolve that each validator is in the service. If validator is
00256         not, log a warning.
00257 
00258         We could replace strings with class refs and keep things impl
00259         the ivalidator in the list.
00260 
00261         Note: this is not compat with aq_ things like scripts with __call__
00262         """
00263         chainname = 'Validator_%s' % self.getName()
00264 
00265         if isinstance(self.validators, dict):
00266             raise NotImplementedError, 'Please use the new syntax with validation chains'
00267         elif IValidationChain.isImplementedBy(self.validators):
00268             validators = self.validators
00269         elif IValidator.isImplementedBy(self.validators):
00270             validators = ValidationChain(chainname, validators=self.validators)
00271         elif type(self.validators) in (TupleType, ListType, StringType):
00272             if len(self.validators):
00273                 # got a non empty list or string - create a chain
00274                 try:
00275                     validators = ValidationChain(chainname, validators=self.validators)
00276                 except (UnknowValidatorError, FalseValidatorError), msg:
00277                     log("WARNING: Disabling validation for %s: %s" % (self.getName(), msg))
00278                     validators = ()
00279             else:
00280                 validators = ()
00281         else:
00282             log('WARNING: Unknow validation %s. Disabling!' % self.validators)
00283             validators = ()
00284 
00285         if not self.required:
00286             if validators == ():
00287                 validators = ValidationChain(chainname)
00288             if len(validators):
00289                 # insert isEmpty validator at position 0 if first validator
00290                 # is not isEmpty
00291                 if not validators[0][0].name.startswith('isEmpty'):
00292                     validators.insertSufficient('isEmptyNoError')
00293                     #validators.insertSufficient('isEmpty')
00294             else:
00295                 validators.insertSufficient('isEmpty')
00296 
00297         self.validators = validators

Here is the call graph for this function:

def Archetypes.Field.Field._widgetLayer (   self) [private]
instantiate the widget if a class was given and call
widget.populateProps

Definition at line 242 of file Field.py.

00242 
00243     def _widgetLayer(self):
00244         """
00245         instantiate the widget if a class was given and call
00246         widget.populateProps
00247         """
00248         if shasattr(self, 'widget'):
00249             if type(self.widget) in (ClassType, type(Base)):
00250                 self.widget = self.widget()
00251             self.widget.populateProps(self)

Here is the call graph for this function:

def Archetypes.Field.Field.checkExternalEditor (   self,
  instance 
)
Checks if the user may edit this field and if
external editor is enabled on this instance 

Definition at line 550 of file Field.py.

00550 
00551     def checkExternalEditor(self, instance):
00552         """ Checks if the user may edit this field and if
00553         external editor is enabled on this instance """
00554 
00555         pp = getToolByName(instance, 'portal_properties')
00556         sp = getattr(pp, 'site_properties', None)
00557         if sp is not None:
00558             if getattr(sp, 'ext_editor', None) \
00559                    and self.checkPermission(mode='edit', instance=instance):
00560                 return True
00561         return None

Here is the call graph for this function:

def Archetypes.Field.Field.checkPermission (   self,
  mode,
  instance 
)
Check whether the security context allows the given permission on
the given object.

Arguments:

mode -- 'w' for write or 'r' for read
instance -- The object being accessed according to the permission

Definition at line 507 of file Field.py.

00507 
00508     def checkPermission(self, mode, instance):
00509         """
00510         Check whether the security context allows the given permission on
00511         the given object.
00512 
00513         Arguments:
00514 
00515         mode -- 'w' for write or 'r' for read
00516         instance -- The object being accessed according to the permission
00517         """
00518         if mode in ('w', 'write', 'edit', 'set'):
00519             perm = self.write_permission
00520         elif mode in ('r', 'read', 'view', 'get'):
00521             perm = self.read_permission
00522         else:
00523             return None
00524         return getSecurityManager().checkPermission( perm, instance )
00525 

Here is the caller graph for this function:

def Archetypes.Field.Field.copy (   self,
  name = None 
)
Return a copy of field instance, consisting of field name and
properties dictionary. field name can be changed to given name.

Definition at line 220 of file Field.py.

00220 
00221     def copy(self, name=None):
00222         """
00223         Return a copy of field instance, consisting of field name and
00224         properties dictionary. field name can be changed to given name.
00225         """
00226         cdict = dict(vars(self))
00227         cdict.pop('__name__')
00228         # Widget must be copied separatedly
00229         widget = cdict['widget']
00230         del cdict['widget']
00231         properties = deepcopy(cdict)
00232         properties['widget'] = widget.copy()
00233         name = name is not None and name or self.getName()
00234         return self.__class__(name, **properties)
00235 
    

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getAccessor (   self,
  instance 
)
Return the accessor method for getting data out of this
field

Definition at line 602 of file Field.py.

00602 
00603     def getAccessor(self, instance):
00604         """Return the accessor method for getting data out of this
00605         field"""
00606         if self.accessor:
00607             return getattr(instance, self.accessor, None)
00608         return None

def Archetypes.Field.Field.getDefault (   self,
  instance 
)
Return the default value to be used for initializing this
field

Definition at line 579 of file Field.py.

00579 
00580     def getDefault(self, instance):
00581         """Return the default value to be used for initializing this
00582         field"""
00583         dm = self.default_method
00584         if dm:
00585             if isinstance(dm, basestring) and shasattr(instance, dm):
00586                 method = getattr(instance, dm)
00587                 return method()
00588             elif callable(dm):
00589                 return dm()
00590             else:
00591                 raise ValueError('%s.default_method is neither a method of %s'
00592                                  ' nor a callable' % (self.getName(),
00593                                                       instance.__class__))
00594         
00595         if not self.default:
00596             default_adapter = component.queryAdapter(instance, IFieldDefaultProvider, name=self.__name__)
00597             if default_adapter is not None:
00598                 return default_adapter()
00599                 
00600         return self.default

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.getEditAccessor (   self,
  instance 
)
Return the accessor method for getting raw data out of this
field e.g.: for editing

Definition at line 610 of file Field.py.

00610 
00611     def getEditAccessor(self, instance):
00612         """Return the accessor method for getting raw data out of this
00613         field e.g.: for editing
00614         """
00615         if self.edit_accessor:
00616             return getattr(instance, self.edit_accessor, None)
00617         return None

returns the internationalization domain for translation 

Definition at line 678 of file Field.py.

00678 
00679     def getI18nDomain(self):
00680         """ returns the internationalization domain for translation """
00681         pass
00682 
00683 #InitializeClass(Field)
00684 setSecurity(Field)

def Archetypes.Field.Field.getIndexAccessor (   self,
  instance 
)
Return the index accessor, i.e. the getter for an indexable
value.

Reimplemented in Archetypes.Field.FileField.

Definition at line 627 of file Field.py.

00627 
00628     def getIndexAccessor(self, instance):
00629         """Return the index accessor, i.e. the getter for an indexable
00630         value."""
00631         return getattr(instance, self.getIndexAccessorName())

Here is the call graph for this function:

Return the index accessor's name defined by the
'index_method' field property.

Definition at line 633 of file Field.py.

00633 
00634     def getIndexAccessorName(self):
00635         """Return the index accessor's name defined by the
00636         'index_method' field property."""
00637         if not hasattr(self, 'index_method'):
00638             return self.accessor
00639         elif self.index_method == '_at_accessor':
00640             return self.accessor
00641         elif self.index_method == '_at_edit_accessor':
00642             return self.edit_accessor or self.accessor
00643 
00644         # If index_method is not a string, we raise ValueError (this
00645         # is actually tested for in test_extensions_utils):
00646         elif not isinstance(self.index_method, (str, unicode)):
00647             raise ValueError("Bad index accessor value : %r"
00648                              % self.index_method)
00649         else:
00650             return self.index_method

Here is the caller graph for this function:

def Archetypes.Field.Field.getMutator (   self,
  instance 
)
Return the mutator method used for changing the value
of this field

Definition at line 619 of file Field.py.

00619 
00620     def getMutator(self, instance):
00621         """Return the mutator method used for changing the value
00622         of this field"""
00623         if self.mutator:
00624             return getattr(instance, self.mutator, None)
00625         return None

Return the name of this field as a string

Definition at line 569 of file Field.py.

00569 
00570     def getName(self):
00571         """Return the name of this field as a string"""
00572         return self.__name__

Here is the caller graph for this function:

Return the type of this field as a string

Definition at line 574 of file Field.py.

00574 
00575     def getType(self):
00576         """Return the type of this field as a string"""
00577         return className(self)

Here is the call graph for this function:

Return the widget name that is configured for this field as
a string

Definition at line 563 of file Field.py.

00563 
00564     def getWidgetName(self):
00565         """Return the widget name that is configured for this field as
00566         a string"""
00567         return self.widget.getName()

def Archetypes.Field.Field.isLanguageIndependent (   self,
  instance 
)
Get the language independed flag for i18n content

Definition at line 672 of file Field.py.

00672 
00673     def isLanguageIndependent(self, instance):
00674         """Get the language independed flag for i18n content
00675         """
00676         return self.languageIndependent

Utility method for converting a Field to a string for the
purpose of comparing fields.  This comparison is used for
determining whether a schema has changed in the auto update
function. Right now it's pretty crude.

Definition at line 652 of file Field.py.

00652 
00653     def toString(self):
00654         """Utility method for converting a Field to a string for the
00655         purpose of comparing fields.  This comparison is used for
00656         determining whether a schema has changed in the auto update
00657         function. Right now it's pretty crude."""
00658         # TODO fixme
00659         s = '%s(%s): {' % ( self.__class__.__name__, self.__name__ )
00660         sorted_keys = self._properties.keys()
00661         sorted_keys.sort()
00662         for k in sorted_keys:
00663             value = getattr( self, k, self._properties[k] )
00664             if k == 'widget':
00665                 value = value.__class__.__name__
00666             if type(value) is UnicodeType:
00667                 value = value.encode('utf-8')
00668             s = s + '%s:%s,' % (k, value )
00669         s = s + '}'
00670         return s

Here is the caller graph for this function:

def Archetypes.Field.Field.validate (   self,
  value,
  instance,
  errors = None,
  kwargs 
)
Validate passed-in value using all field validators.
Return None if all validations pass; otherwise, return failed
result returned by validator

Definition at line 299 of file Field.py.

00299 
00300     def validate(self, value, instance, errors=None, **kwargs):
00301         """
00302         Validate passed-in value using all field validators.
00303         Return None if all validations pass; otherwise, return failed
00304         result returned by validator
00305         """
00306         if errors is None:
00307             errors = {}
00308         name = self.getName()
00309         if errors and errors.has_key(name):
00310             return True
00311 
00312         if self.required:
00313             res = self.validate_required(instance, value, errors)
00314             if res is not None:
00315                 return res
00316 
00317         if self.enforceVocabulary:
00318             res = self.validate_vocabulary(instance, value, errors)
00319             if res is not None:
00320                 return res
00321 
00322         res = instance.validate_field(name, value, errors)
00323         if res is not None:
00324             return res
00325 
00326         if self.validators:
00327             res = self.validate_validators(value, instance, errors, **kwargs)
00328             if res is not True:
00329                 return res
00330 
00331         # all ok
00332         return None

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.validate_required (   self,
  instance,
  value,
  errors 
)

Reimplemented in Archetypes.Field.PhotoField, Archetypes.Field.FixedPointField, Archetypes.Field.FloatField, Archetypes.Field.IntegerField, Archetypes.Field.DateTimeField, and Archetypes.Field.FileField.

Definition at line 347 of file Field.py.

00347 
00348     def validate_required(self, instance, value, errors):
00349         if not value:
00350             request = aq_get(instance, 'REQUEST')
00351             label = self.widget.Label(instance)
00352             name = self.getName()
00353             if isinstance(label, Message):
00354                 label = translate(label, context=request)
00355             error = _(u'error_required',
00356                       default=u'${name} is required, please correct.',
00357                       mapping={'name': label})
00358             error = translate(error, context=request)
00359             errors[name] = error
00360             return error
00361         return None

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.validate_validators (   self,
  value,
  instance,
  errors,
  kwargs 
)

Definition at line 334 of file Field.py.

00334 
00335     def validate_validators(self, value, instance, errors, **kwargs):
00336         """
00337         """
00338         if self.validators:
00339             result = self.validators(value, instance=instance, errors=errors,
00340                                      field=self, **kwargs)
00341         else:
00342             result = True
00343 
00344         if result is not True:
00345             return result

Here is the caller graph for this function:

def Archetypes.Field.Field.validate_vocabulary (   self,
  instance,
  value,
  errors 
)
Make sure value is inside the allowed values
for a given vocabulary

Definition at line 363 of file Field.py.

00363 
00364     def validate_vocabulary(self, instance, value, errors):
00365         """Make sure value is inside the allowed values
00366         for a given vocabulary"""
00367         badvalues = []
00368         if value:
00369             # coerce value into a list called values
00370             values = value
00371             if type(value) in STRING_TYPES:
00372                 values = [value]
00373             elif type(value) == BooleanType:
00374                 values = [str(value)]
00375             elif type(value) not in (TupleType, ListType):
00376                 raise TypeError("Field value type error: %s" % type(value))
00377             vocab = self.Vocabulary(instance)
00378             # filter empty
00379             values = [instance.unicodeEncode(v)
00380                       for v in values if v.strip()]
00381             # extract valid values from vocabulary
00382             valids = []
00383             for v in vocab:
00384                 if type(v) in (TupleType, ListType):
00385                     v = v[0]
00386                 if not type(v) in STRING_TYPES:
00387                     v = str(v)
00388                 valids.append(instance.unicodeEncode(v))
00389             # check field values
00390             badvalues = [val for val in values if not val in valids]
00391 
00392         error = None
00393         if badvalues:
00394             request = aq_get(instance, 'REQUEST')
00395             label = self.widget.Label(instance)
00396             if isinstance(label, Message):
00397                 label = translate(label, context=request)
00398             if isinstance(val, Message):
00399                 val = translate(val, context=request)
00400             error = _( u'error_vocabulary',
00401                 default=u'Values ${val} is not allowed for vocabulary of element ${label}.',
00402                 mapping={'val': unicode(badvalues), 'name': label})
00403             error = translate(error, context=request)
00404             errors[self.getName()] = error
00405         return error

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.Vocabulary (   self,
  content_instance = None 
)
Returns a DisplayList.

Uses self.vocabulary as source.

1) Static vocabulary

   - is already a DisplayList
   - is a list of 2-tuples with strings (see above)
   - is a list of strings (in this case a DisplayList
     with key=value will be created)

2) Dynamic vocabulary:

   - precondition: a content_instance is given.

   - has to return a:

* DisplayList or
* list of strings or
* list of 2-tuples with strings:
    '[("key1","value 1"),("key 2","value 2"),]'

   - the output is postprocessed like a static vocabulary.

   - vocabulary is a string:
if a method with the name of the string exists it will be called

   - vocabulary is a class implementing IVocabulary:
the "getDisplayList" method of the class will be called.

3) Zope 3 vocabulary factory vocabulary

    - precondition: a content_instance is given
    
    - self.vocabulary_factory is given
    
    - a named utility providing zope.schema.interfaces.IVocbularyFactory 
      exists for the name self.vocabulary_factory.

Reimplemented in Archetypes.Field.ReferenceField.

Definition at line 407 of file Field.py.

00407 
00408     def Vocabulary(self, content_instance=None):
00409         """
00410         Returns a DisplayList.
00411 
00412         Uses self.vocabulary as source.
00413 
00414         1) Static vocabulary
00415 
00416            - is already a DisplayList
00417            - is a list of 2-tuples with strings (see above)
00418            - is a list of strings (in this case a DisplayList
00419              with key=value will be created)
00420 
00421         2) Dynamic vocabulary:
00422 
00423            - precondition: a content_instance is given.
00424 
00425            - has to return a:
00426 
00427                 * DisplayList or
00428                 * list of strings or
00429                 * list of 2-tuples with strings:
00430                     '[("key1","value 1"),("key 2","value 2"),]'
00431 
00432            - the output is postprocessed like a static vocabulary.
00433 
00434            - vocabulary is a string:
00435                 if a method with the name of the string exists it will be called
00436 
00437            - vocabulary is a class implementing IVocabulary:
00438                 the "getDisplayList" method of the class will be called.
00439 
00440         3) Zope 3 vocabulary factory vocabulary
00441         
00442             - precondition: a content_instance is given
00443             
00444             - self.vocabulary_factory is given
00445             
00446             - a named utility providing zope.schema.interfaces.IVocbularyFactory 
00447               exists for the name self.vocabulary_factory.
00448 
00449         """
00450         value = self.vocabulary
00451         
00452         # Attempt to get the value from a a vocabulary factory if one was given
00453         # and no explicit vocabulary was set
00454         if not isinstance(value, DisplayList) and not value:
00455             factory_name = getattr(self, 'vocabulary_factory', None)
00456             if factory_name is not None:
00457                 factory = component.getUtility(schema.interfaces.IVocabularyFactory, name=factory_name)
00458                 factory_context = content_instance
00459                 if factory_context is None:
00460                     factory_context = self
00461                 value = DisplayList([(t.value, t.title or t.token) for t in factory(factory_context)])
00462                     
00463         if not isinstance(value, DisplayList):
00464 
00465             if content_instance is not None and isinstance(value, basestring):
00466                 # Dynamic vocabulary by method on class of content_instance
00467                 method = getattr(content_instance, value, None)
00468                 if method and callable(method):
00469                     args = []
00470                     kw = {'content_instance' : content_instance,
00471                           'field' : self}
00472                     value = mapply(method, *args, **kw)
00473             elif content_instance is not None and \
00474                  IVocabulary.isImplementedBy(value):
00475                 # Dynamic vocabulary provided by a class that
00476                 # implements IVocabulary
00477                 value = value.getDisplayList(content_instance)
00478 
00479             # Post process value into a DisplayList
00480             # Templates will use this interface
00481             sample = value[:1]
00482             if isinstance(sample, DisplayList):
00483                 # Do nothing, the bomb is already set up
00484                 pass
00485             elif isinstance(sample, (list, tuple)):
00486                 # Assume we have ((value, display), ...)
00487                 # and if not ('', '', '', ...)
00488                 if sample and not isinstance((sample[0]), (list, tuple)):
00489                     # if not a 2-tuple
00490                     value = zip(value, value)
00491                 value = DisplayList(value)
00492             elif len(sample) and isinstance(sample[0], basestring):
00493                 value = DisplayList(zip(value, value))
00494             else:
00495                 log('Unhandled type in Vocab')
00496                 log(value)
00497 
00498         if content_instance:
00499             # Translate vocabulary
00500             i18n_domain = (getattr(self, 'i18n_domain', None) or
00501                           getattr(self.widget, 'i18n_domain', None))
00502 
00503             return Vocabulary(value, content_instance, i18n_domain)
00504 
00505         return value

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.Field.Field.writeable (   self,
  instance,
  debug = False 
)

Definition at line 527 of file Field.py.

00527 
00528     def writeable(self, instance, debug=False):
00529         if 'w' not in self.mode:
00530             if debug:
00531                 log("Tried to update %s:%s but field is not writeable." % \
00532                     (instance.portal_type, self.getName()))
00533             return False
00534 
00535         method = self.getMutator(instance)
00536         if not method:
00537             if debug:
00538                 log("No method %s on %s." % (self.mutator, instance))
00539             return False
00540 
00541         if not self.checkPermission('edit', instance):
00542             if debug:
00543                 log("User %s tried to update %s:%s but "
00544                     "doesn't have enough permissions." %
00545                     (_getAuthenticatedUser(instance).getId(),
00546                      instance.portal_type, self.getName()))
00547             return False
00548         return True

Here is the call graph for this function:


Member Data Documentation

Archetypes.Field.Field.__implements__ = IField,ILayerContainer [static, private]

Definition at line 209 of file Field.py.

dictionary Archetypes.Field.Field._properties [static, private]

Definition at line 638 of file Field.py.

tuple Archetypes.Field.Field.security = ClassSecurityInfo() [static]

Definition at line 296 of file Field.py.

Definition at line 249 of file Field.py.


The documentation for this class was generated from the following file: