def user_schemata(self): """Includes any behaviours that have been added""" schematas = [self.core_user_schema] for behavior_schema in getAdditionalSchemata( portal_type=USER_PORTAL_TYPE): schematas.append(behavior_schema) return schematas
def modifiedDexterity(obj, event): """ a dexterity based object was modified """ pu = getToolByName(obj, 'portal_url', None) if pu is None: # `getObjectFromLinks` is not possible without access # to `portal_url` return rc = getToolByName(obj, 'reference_catalog', None) if rc is None: # `updateReferences` is not possible without access # to `reference_catalog` return fti = getUtility(IDexterityFTI, name=obj.portal_type) schema = fti.lookupSchema() additional_schema = getAdditionalSchemata(context=obj, portal_type=obj.portal_type) schemas = [i for i in additional_schema] + [schema] refs = set() for schema in schemas: for name, field in getFieldsInOrder(schema): if isinstance(field, RichText): # Only check for "RichText" ? value = getattr(schema(obj), name) if not value: continue links = extractLinks(value.raw) refs |= getObjectsFromLinks(obj, links) updateReferences(IReferenceable(obj), referencedRelationship, refs)
def copy_fields(self, translation): fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in \ utils.getAdditionalSchemata(self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) for schema in schemas: for field_name in schema: if field_name in EXCLUDES: continue if not ILanguageIndependentField.providedBy(schema[field_name]): value = getattr(schema(self.context), field_name, _marker) if IRelationValue.providedBy(value): obj = value.to_object adapter = queryAdapter(translation, ILanguage) trans_obj = ITranslationManager(obj).get_translation(adapter.get_language()) if trans_obj: intids = component.getUtility(IIntIds) value = RelationValue(intids.getId(trans_obj)) if not (value == _marker): # We check if not (value == _marker) because z3c.relationfield has an __eq__ setattr(schema(translation), field_name, value)
def modifiedDexterity(obj, event): """ a dexterity based object was modified """ pu = getToolByName(obj, 'portal_url', None) if pu is None: # `getObjectFromLinks` is not possible without access # to `portal_url` return rc = getToolByName(obj, 'reference_catalog', None) if rc is None: # `updateReferences` is not possible without access # to `reference_catalog` return fti = getUtility(IDexterityFTI, name=obj.portal_type) fields = [] schema = fti.lookupSchema() additional_schema = getAdditionalSchemata(context=obj, portal_type=obj.portal_type) schemas = [i for i in additional_schema] + [schema] refs = set() for schema in schemas: for name,field in getFieldsInOrder(schema): if isinstance(field, RichText): # Only check for "RichText" ? value = getattr(schema(obj), name) if not value: continue links = extractLinks(value.raw) refs |= getObjectsFromLinks(obj, links) updateReferences(IReferenceable(obj), referencedRelationship, refs)
def get_jsonschema_for_fti(fti, context, request, excluded_fields=None): """Build a complete JSON schema for the given FTI. """ if excluded_fields is None: excluded_fields = [] schema = fti.lookupSchema() additional_schemata = tuple(getAdditionalSchemata(portal_type=fti.id)) fieldsets = get_fieldsets(context, request, schema, additional_schemata) # Build JSON schema properties properties = get_jsonschema_properties(context, request, fieldsets, excluded_fields=excluded_fields) # Determine required fields required = [] for field in iter_fields(fieldsets): if field.field.required: required.append(field.field.getName()) # Include field modes for field in iter_fields(fieldsets): if field.mode: properties[field.field.getName()]['mode'] = field.mode return { 'type': 'object', 'title': translate(fti.Title(), context=getRequest()), 'properties': properties, 'required': required, 'fieldsets': get_fieldset_infos(fieldsets), }
def copy_fields(self, translation): fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in \ utils.getAdditionalSchemata(self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) doomed = False for schema in schemas: for field_name in schema: if ILanguageIndependentField.providedBy(schema[field_name]): doomed = True value = getattr(schema(self.context), field_name, _marker) if IRelationValue.providedBy(value): obj = value.to_object adapter = queryAdapter(translation, ILanguage) trans_obj = ITranslationManager(obj)\ .get_translation(adapter.get_language()) if trans_obj: intids = component.getUtility(IIntIds) value = RelationValue(intids.getId(trans_obj)) if not (value == _marker): # We check if not (value == _marker) because # z3c.relationfield has an __eq__ setattr(schema(translation), field_name, value) # If at least one field has been copied over to the translation # we need to inform subscriber to trigger an ObjectModifiedEvent # on that translation. return doomed
def _iter_schemata_for_protal_type(self, portal_type): if queryUtility(IDexterityFTI, name=portal_type): # is dexterity fti = getUtility(IDexterityFTI, name=portal_type) yield fti.lookupSchema() for schema in getAdditionalSchemata(portal_type=portal_type): yield schema
def iter_schemata_for_protal_type(self, portal_type): fti = queryUtility(IDexterityFTI, name=portal_type) if fti is None: return yield fti.lookupSchema() for schema in getAdditionalSchemata(portal_type=portal_type): yield schema
def get_schema_values(self): values = {} for schema in getAdditionalSchemata(self): for fieldname, field in getFieldsInOrder(schema): key = '{}.{}'.format(schema.__name__, fieldname) if key not in TEMPLATABLE_FIELDS: continue values[key] = getattr(field.interface(self), fieldname) return values
def _getDexterityFields(self, portal_type): fti = getUtility(IDexterityFTI, name=portal_type) schema = fti.lookupSchema() fields = {} for name in schema: fields[name] = schema[name] for schema in getAdditionalSchemata(portal_type=portal_type): for name in schema: fields[name] = schema[name] return fields
def view_schema(self): additionnal = list(getAdditionalSchemata(portal_type=self.fti_id)) fields = field.Fields(self.sqlschema) additionnal_fields = field.Fields(*additionnal) view_fields = [] if 'title' in additionnal_fields: view_fields.append('title') additionnal_fields = additionnal_fields.select(*view_fields) additionnal_fields += fields return additionnal_fields
def update_schema(self): additionnal = list(getAdditionalSchemata(portal_type=self.fti_id)) fields = field.Fields(self.sqlschema) additionnal_fields = field.Fields(*additionnal) update_fields = [] for field_name in additionnal_fields: if field_name in self.fieldnames.keys(): update_fields.append(field_name) additionnal_fields = additionnal_fields.select(*update_fields) fields += additionnal_fields return fields
def whitelist_form_fields(form, whitlisted_fields): """Removes all fields instead the whitelisted fields from the form. """ for schema in getAdditionalSchemata(form): behavior_interface_name = schema.__name__ for fieldname in schema: full_name = '{}.{}'.format(behavior_interface_name, fieldname) if full_name in whitlisted_fields: continue remove(form, fieldname, behavior_interface_name)
def test_getAdditionalSchemata(self): from plone.dexterity.interfaces import IDexterityFTI from plone.behavior.interfaces import IBehavior from plone.autoform.interfaces import IFormFieldProvider from zope.interface import Interface from zope.interface import providedBy class IBehaviorInterface(Interface): pass class IBehaviorSchema(Interface): pass behavior_mock = self.mocker.mock() fti_mock = self.mocker.proxy(DexterityFTI(u'testtype')) provider_mock = self.mocker.mock() portal_type = 'prefix_0_type_0_schema' behavior_name = 'behavior_0' self.expect( fti_mock.behaviors ).result( (behavior_name, ) ) self.expect( behavior_mock.interface ).result( IBehaviorInterface ).count(2) provider_mock(IBehaviorInterface) self.mocker.result(IBehaviorSchema) self.mock_utility(behavior_mock, IBehavior, behavior_name) self.mock_utility(fti_mock, IDexterityFTI, portal_type) self.mock_adapter( provider_mock, IFormFieldProvider, (providedBy(IBehaviorInterface), ) ) self.replay() generator = utils.getAdditionalSchemata(None, portal_type) schematas = tuple(generator) self.assertEqual(len(schematas), 1) schemata = schematas[0] self.assertTrue(schemata is IBehaviorSchema)
def findTextAreas(obj): fti = getUtility(IDexterityFTI, name=obj.portal_type) schema = fti.lookupSchema() additional_schema = getAdditionalSchemata( context=obj, portal_type=obj.portal_type) schemas = [i for i in additional_schema] + [schema] for schema in schemas: for name, field in getFieldsInOrder(schema): if isinstance(field, RichText): value = getattr(schema(obj), name) if not value or not getattr(value, 'raw', None): continue yield value.raw
def get_jsonschema_for_fti(fti, context, request, excluded_fields=None): """Build a complete JSON schema for the given FTI. """ if excluded_fields is None: excluded_fields = [] # We try..except lookupSchema here, so we still get FTI information # through /@types/{typeid} for non-DX type, notably the "Plone Site" type. try: schema = fti.lookupSchema() except AttributeError: schema = None fieldsets = () additional_schemata = () else: additional_schemata = tuple(getAdditionalSchemata(portal_type=fti.id)) fieldsets = get_fieldsets(context, request, schema, additional_schemata) # Mangle the properties a bit to add widgets hints schemas = (schema, ) + additional_schemata # Build JSON schema properties properties = get_jsonschema_properties(context, request, fieldsets, excluded_fields=excluded_fields, tagged_values=get_tagged_values( schemas, WIDGETS_KEY)) # Determine required fields required = [] for field in iter_fields(fieldsets): if field.field.required: required.append(field.field.getName()) # Include field modes for field in iter_fields(fieldsets): if field.mode: properties[field.field.getName()]['mode'] = field.mode return { 'type': 'object', 'title': translate(fti.Title(), context=getRequest()), 'properties': json_compatible(properties), 'required': required, 'fieldsets': get_fieldset_infos(fieldsets), 'layouts': getattr(fti, 'view_methods', []), }
def getLanguageIndependent(context): portal_type = context.portal_type fti = getUtility(IDexterityFTI, name=portal_type) schemata = getAdditionalSchemata(context=context, portal_type=portal_type) schemas = tuple(schemata) + (fti.lookupSchema(), ) fields = set() for schema in schemas: entries = mergedTaggedValueList(schema, LANGUAGE_INDEPENDENT_KEY) for interface, name, value in entries: field = schema[name] fields.add(field) return fields
def copy_fields(self, translation): fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in \ utils.getAdditionalSchemata(self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) for schema in schemas: for field_name in schema: if ILanguageIndependentField.providedBy(schema[field_name]): value = getattr(self.context, field_name) setattr(translation, field_name, value)
def get_jsonschema_for_fti(fti, context, request, excluded_fields=None): """Build a complete JSON schema for the given FTI.""" if excluded_fields is None: excluded_fields = [] # We try..except lookupSchema here, so we still get FTI information # through /@types/{typeid} for non-DX type, notably the "Plone Site" type. try: schema = fti.lookupSchema() except AttributeError: schema = None fieldsets = () additional_schemata = () else: additional_schemata = tuple(getAdditionalSchemata(portal_type=fti.id)) fieldsets = get_fieldsets(context, request, schema, additional_schemata) # Build JSON schema properties properties = get_jsonschema_properties( context, request, fieldsets, excluded_fields=excluded_fields ) required = [] for field in iter_fields(fieldsets): name = field.field.getName() # Determine required fields if field.field.required: required.append(name) # Include field modes if field.mode: properties[name]["mode"] = field.mode # Include behavior if name in properties: behavior = queryUtility(IBehavior, name=field.interface.__identifier__) properties[name]["behavior"] = ( getattr(behavior, "name", None) or field.interface.__identifier__ ) return { "type": "object", "title": translate(fti.Title(), context=getRequest()), "properties": IJsonCompatible(properties), "required": required, "fieldsets": get_fieldset_infos(fieldsets), "layouts": getattr(fti, "view_methods", []), }
def retrieveLinks(self): """Finds all links from the object and return them.""" fti = getUtility(IDexterityFTI, name=self.context.portal_type) schema = fti.lookupSchema() additional_schema = getAdditionalSchemata( context=self.context, portal_type=self.context.portal_type) schemas = [i for i in additional_schema] + [schema] links = set() for schema in schemas: for name, field in getFieldsInOrder(schema): if isinstance(field, RichText): value = getattr(schema(self.context), name) if not value or not getattr(value, 'raw', None): continue links |= set(extractLinks(value.raw)) return links
def findTextAreas(obj): if not obj: yield [] return fti = getUtility(IDexterityFTI, name=obj.portal_type) schema = fti.lookupSchema() additional_schema = getAdditionalSchemata( context=obj, portal_type=obj.portal_type) schemas = [i for i in additional_schema] + [schema] for schema in schemas: for name, field in getFieldsInOrder(schema): if isinstance(field, RichText): value = getattr(schema(obj), name) if not value or not getattr(value, 'raw', None): continue yield value.raw
def getAllFieldSets(fti, portal_type): fieldsets = set() def extractFieldSets(schema): retval = [] for baseschema in schema.__bases__: retval.extend(extractFieldSets(baseschema)) for fieldset in schema.queryTaggedValue(FIELDSETS_KEY) or []: retval.append(fieldset) return retval for schema in [fti.lookupSchema()] + [x for x in getAdditionalSchemata(portal_type=portal_type)]: for fieldset in extractFieldSets(schema): fieldsets.add(fieldset) return fieldsets
def has_independent_fields(self): fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in \ utils.getAdditionalSchemata(self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) for schema in schemas: for field_name in schema: if ILanguageIndependentField.providedBy(schema[field_name]): return True return False
def validate(self, filedata): """ Validates the file's column headers. :rtype: bool """ # check for core user fields core_fields = schema.getFields(self.core_user_schema).values() required_core_user_fields = set( [x.getName() for x in core_fields if x.required]) optional_core_user_fields = set([ x.getName() for x in core_fields if x.getName() not in required_core_user_fields ]) file_headers = filedata.headers if not file_headers: raise tablib.core.HeadersNeeded('No header row found') headers = set(self._normalise_headers(file_headers)) if not required_core_user_fields <= headers: missing = required_core_user_fields - headers raise custom_exc.MissingCoreFields( u"The following required fields are missing: {}".format( ', '.join(missing)), ) # check all columns in csv are used # (password is a special case hidden from edit schematas # so we include it manually here) additional_fields = [ 'password', ] for behavior_schema in getAdditionalSchemata( portal_type=USER_PORTAL_TYPE): additional_fields.extend(behavior_schema.names()) all_user_fields = set() all_user_fields |= set(additional_fields) all_user_fields |= required_core_user_fields all_user_fields |= optional_core_user_fields if not headers <= all_user_fields: extra = headers - all_user_fields raise custom_exc.ExtraneousFields( u"There are extraneous fields in the input file: {0}".format( ', '.join(extra), ), ) return True
def initialize(self): """Initialize the view class.""" fieldId = self.request.get('fieldId', '').split('-')[-1] typeOrDottedname = self.request.get('typeOrDottedname') context = aq_inner(self.context) if typeOrDottedname == context.portal_type and shasattr( context, 'Schema'): # Archetype field = context.Schema().getField(fieldId) self.multivalued = field.multiValued self.widget = field.widget else: fti = queryUtility(IDexterityFTI, name=typeOrDottedname) if fti is None: # Must be a standalone z3c.form forms then. klass = utils.resolveDottedName(typeOrDottedname) field = klass(self.context, self.request).fields.get(fieldId).field self.widget = FieldWidget( field, UserAndGroupSelectionWidget(field, self.request)) self.multivalued = ICollection.providedBy(field) else: # Dexterity schema = fti.lookupSchema() field = schema.get(fieldId) if field is None: # The field might be defined in a behavior schema. # Get the behaviors from either the context or the # portal_type (but not both at the same time). if self.request.get('ignoreContext'): context = None portal_type = typeOrDottedname else: portal_type = None for behavior_schema in \ utils.getAdditionalSchemata(context, portal_type): if behavior_schema is not None: field = behavior_schema.get(fieldId) if field is not None: break self.widget = FieldWidget( field, UserAndGroupSelectionWidget(field, self.request)) self.multivalued = ICollection.providedBy(field) self.memberlookup = MemberLookup(self.context, self.request, self.widget)
def extractFieldsFromDexterityFTI(fti_name, context): fti = getUtility(IDexterityFTI, name=fti_name) def extractFields(schema): retval = [] for baseschema in schema.__bases__: retval.extend(extractFields(baseschema)) for fieldname in schema.names(): retval.append(schema[fieldname]) return retval retval = [] for schema in [fti.lookupSchema()] + [x for x in getAdditionalSchemata(portal_type=fti_name)]: retval.extend(extractFields(schema)) retval.sort(key=lambda x: x.order) return retval
def validate(self, filedata): """ Validates the file's column headers. :rtype: bool """ # check for core user fields required_core_user_fields = set( [x.getName() for x in schema.getFields(self.core_user_schema).values() if x.required] ) file_headers = filedata.headers if not file_headers: raise tablib.core.HeadersNeeded('No header row found') headers = set(self._normalise_headers(file_headers)) if not required_core_user_fields <= headers: missing = required_core_user_fields - headers raise custom_exc.MissingCoreFields( u"The following required fields are missing: {}".format( ', '.join(missing)), ) # check all columns in csv are used # (password is a special case hidden from edit schematas # so we include it manually here) additional_fields = ['password', ] for behavior_schema in getAdditionalSchemata( portal_type=USER_PORTAL_TYPE): additional_fields.extend(behavior_schema.names()) all_user_fields = set() all_user_fields |= set(additional_fields) all_user_fields |= required_core_user_fields if not headers <= all_user_fields: extra = headers - all_user_fields raise custom_exc.ExtraneousFields( u"There are extraneous fields in the input file: {0}".format( ', '.join(extra), ), ) return True
def get_dexterity_schemas(context=None, portal_type=None): """ Utility method to get all schemas for a dexterity object. IMPORTANT: Either context or portal_type must be passed in, NOT BOTH. The idea is that for edit forms context is passed in and for add forms where we don't have a valid context we pass in portal_type. This builds on getAdditionalSchemata, which works the same way. """ if context is not None: portal_type = context.portal_type fti = component.getUtility(IDexterityFTI, name=portal_type) schemas = [fti.lookupSchema()] for behavior_schema in \ utils.getAdditionalSchemata(context=context, portal_type=portal_type): if behavior_schema is not None: schemas.append(behavior_schema) return schemas
def initialize(self): """Initialize the view class.""" fieldId = self.request.get('fieldId','').split('-')[-1] typeOrDottedname = self.request.get('typeOrDottedname') context = aq_inner(self.context) if typeOrDottedname == context.portal_type and shasattr(context, 'Schema'): # Archetype field = context.Schema().getField(fieldId) self.multivalued = field.multiValued self.widget = field.widget else: fti = queryUtility(IDexterityFTI, name=typeOrDottedname) if fti is None: # Must be a standalone z3c.form forms then. klass = utils.resolveDottedName(typeOrDottedname) field = klass(self.context, self.request).fields.get(fieldId).field self.widget = FieldWidget(field, UserAndGroupSelectionWidget(field, self.request)) self.multivalued = ICollection.providedBy(field) else: # Dexterity schema = fti.lookupSchema() field = schema.get(fieldId) if field is None: # The field might be defined in a behavior schema. # Get the behaviors from either the context or the # portal_type (but not both at the same time). if self.request.get('ignoreContext'): context = None portal_type = typeOrDottedname else: portal_type = None for behavior_schema in \ utils.getAdditionalSchemata(context, portal_type): if behavior_schema is not None: field = behavior_schema.get(fieldId) if field is not None: break self.widget = FieldWidget(field, UserAndGroupSelectionWidget(field, self.request)) self.multivalued = ICollection.providedBy(field) self.memberlookup = MemberLookup(self.context, self.request, self.widget)
def modifiedDexterity(obj, event): """ a dexterity based object was modified """ if not check_linkintegrity_dependencies(obj): return fti = getUtility(IDexterityFTI, name=obj.portal_type) schema = fti.lookupSchema() additional_schema = getAdditionalSchemata(context=obj, portal_type=obj.portal_type) schemas = [i for i in additional_schema] + [schema] refs = set() for schema in schemas: for name, field in getFieldsInOrder(schema): if isinstance(field, RichText): # Only check for "RichText" ? value = getattr(schema(obj), name) if not value or not getattr(value, 'raw', None): continue links = extractLinks(value.raw) refs |= getObjectsFromLinks(obj, links) updateReferences(obj, refs)
def get_dexterity_schemas(context=None, portal_type=None): """ Utility method to get all schemas for a dexterity object. IMPORTANT: Either context or portal_type must be passed in, NOT BOTH. The idea is that for edit forms context is passed in and for add forms where we don't have a valid context we pass in portal_type. This builds on getAdditionalSchemata, which works the same way. """ if context is not None: portal_type = context.portal_type fti = component.getUtility(IDexterityFTI, name=portal_type) schemas = [fti.lookupSchema()] for behavior_schema in utils.getAdditionalSchemata( context=context, portal_type=portal_type): if behavior_schema is not None: schemas.append(behavior_schema) return schemas
def test_getAdditionalSchemata(self): from plone.dexterity.interfaces import IDexterityFTI from plone.behavior.interfaces import IBehavior from plone.autoform.interfaces import IFormFieldProvider from zope.interface import Interface from zope.interface import providedBy class IBehaviorInterface(Interface): pass class IBehaviorSchema(Interface): pass behavior_mock = Mock() fti_mock = DexterityFTI(u'testtype') portal_type = 'prefix_0_type_0_schema' behavior_name = 'behavior_0' fti_mock.behaviors = (behavior_name,) behavior_mock.interface = IBehaviorInterface provider_mock = Mock(return_value=IBehaviorSchema) self.mock_utility(behavior_mock, IBehavior, behavior_name) self.mock_utility(fti_mock, IDexterityFTI, portal_type) self.mock_adapter( provider_mock, IFormFieldProvider, (providedBy(IBehaviorInterface), ) ) generator = utils.getAdditionalSchemata(None, portal_type) schematas = tuple(generator) self.assertEqual(len(schematas), 1) schemata = schematas[0] self.assertTrue(schemata is IBehaviorSchema)
def get_translatable_fields(self): field_info = [] fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in dexterityutils.getAdditionalSchemata( self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) for schema in schemas: for field_name in schema: field = schema[field_name] if not ILanguageIndependentField.providedBy(field) \ and field_name != 'language': title = field.title # If the field's title is a translatable Message, get # the correct translation for it. Use fallback in case # we have a combined language code such as da-dk if isinstance(title, Message): trans_util = queryUtility( ITranslationDomain, title.domain) if trans_util: trans_util.setLanguageFallbacks(self.fallbacks) title = trans_util.translate( title, self.language) else: title = translate(title, self.language) # Mark required fields if getattr(field, 'required', False): title = "%s (%s) (*)" % (title, field_name) else: title = "%s (%s)" % (title, field_name) field_info.append(( "%s|%s" % (field_name, schema.__identifier__), title, )) return field_info
def additionalSchemata(self): return getAdditionalSchemata(portal_type=self.fti.getId())
def create_content(self, *args, **kwargs): """Create content and return its UID""" disableCSRFProtection() # XXX: Because kwargs are only supported with robotframework >= 2.8.3, # we must parse them here to support robotframework < 2.8.3. for arg in [x for x in args if '=' in x]: name, value = arg.split('=', 1) kwargs[name] = value assert 'type' in kwargs, u"Keyword arguments must include 'type'." portal_type = kwargs.get('type') portal = getSite() if 'container' in kwargs: pc = getToolByName(portal, 'portal_catalog') uid_or_path = kwargs.pop('container') uid_results =\ pc.unrestrictedSearchResults(UID=uid_or_path) path_results = \ pc.unrestrictedSearchResults( path={'query': uid_or_path.rstrip('/'), 'depth': 0}) container =\ (uid_results or path_results)[0]._unrestrictedGetObject() else: container = portal # if we create 'file' and 'image' kwargs entries, they should not be # used to create the content but be set afterwards create_kwargs = {} create_kwargs.update(kwargs) if HAS_DEXTERITY: if portal_type in ('File', ) and 'file' not in kwargs: pdf_file = os.path.join( os.path.dirname(__file__), 'content', u'file.pdf') value = NamedBlobFile( data=open(pdf_file, 'r').read(), contentType='application/pdf', filename=u'file.pdf' ) kwargs['file'] = value if portal_type in ('Image', 'News Item') and 'image' not in kwargs: prefill_image_types(portal, kwargs) id_ = kwargs.pop('id', None) type_ = kwargs.pop('type') content = None if HAS_DEXTERITY: # The title attribute for Dexterity types needs to be unicode if 'title' in kwargs and isinstance(kwargs['title'], str): kwargs['title'] = kwargs['title'].decode('utf-8') from plone.dexterity.interfaces import IDexterityFTI from plone.dexterity.utils import createContentInContainer try: getUtility(IDexterityFTI, name=type_) content = createContentInContainer( container, type_, **create_kwargs) if id_ is not None and content.id != id_: container.manage_renameObject(content.id, id_) except ComponentLookupError: pass if HAS_DEXTERITY and content: # For dexterity-types, we need a second pass to fill all fields # using their widgets to get e.g. RichText-values created # correctly. fti = getUtility(IDexterityFTI, name=type_) schema = fti.lookupSchema() fields = {} for name in schema: fields[name] = schema[name] for schema in getAdditionalSchemata(portal_type=type_): for name in schema: fields[name] = schema[name] for name, field in fields.items(): widget = queryMultiAdapter((field, getRequest()), IFieldWidget) if widget and name in kwargs: if not IFromUnicode.providedBy(field): value = kwargs[name] elif isinstance(kwargs[name], unicode): value = kwargs[name] else: value = unicode(str(kwargs[name]), 'utf-8', errors='ignore') converter = IDataConverter(widget) dm = queryMultiAdapter((content, field), IDataManager) if dm: dm.set(converter.toFieldValue(value)) if content is None: if id_ is None: normalizer = queryUtility(IURLNormalizer) id_ = normalizer.normalize(kwargs['title']) # It must be Archetypes based content: content = container[container.invokeFactory(type_, id_, **kwargs)] content.processForm() return IUUID(content)
def additionalSchemata(self): return getAdditionalSchemata(portal_type=self.portal_type)
def additionalSchemata(self): # we don't want IContactDetails in behaviors additional_schemata = list(getAdditionalSchemata(context=self.context)) if IContactDetails in additional_schemata: additional_schemata.remove(IContactDetails) return additional_schemata
def get_schemas(obj): """Return a tuple (schema, additional_schemata).""" fti = getUtility(IDexterityFTI, name=obj.portal_type) schema = fti.lookupSchema() additional_schemata = getAdditionalSchemata(context=obj) return (schema, additional_schemata)
def view_schema(self): additionnal = list(getAdditionalSchemata(portal_type=self.fti_id)) fields = field.Fields(*additionnal) fields = fields.select('sql_id') return fields
def additionalSchemata(self): if self._additionalSchemata is not None: return iter(self._additionalSchemata) else: return getAdditionalSchemata(context=self.context)
def create_content(self, *args, **kwargs): """Create content and return its UID""" disableCSRFProtection() # XXX: Because kwargs are only supported with robotframework >= 2.8.3, # we must parse them here to support robotframework < 2.8.3. for arg in [x for x in args if '=' in x]: name, value = arg.split('=', 1) kwargs[name] = value assert 'type' in kwargs, u"Keyword arguments must include 'type'." portal_type = kwargs.get('type') portal = getSite() if 'container' in kwargs: pc = getToolByName(portal, 'portal_catalog') uid_or_path = kwargs.pop('container') uid_results =\ pc.unrestrictedSearchResults(UID=uid_or_path) path_results = \ pc.unrestrictedSearchResults( path={'query': uid_or_path.rstrip('/'), 'depth': 0}) container =\ (uid_results or path_results)[0]._unrestrictedGetObject() else: container = portal # if we create 'file' and 'image' kwargs entries, they should not be # used to create the content but be set afterwards create_kwargs = {} create_kwargs.update(kwargs) if HAS_DEXTERITY: if portal_type in ('File', ) and 'file' not in kwargs: pdf_file = os.path.join(os.path.dirname(__file__), 'content', u'file.pdf') value = NamedBlobFile(data=open(pdf_file, 'r').read(), contentType='application/pdf', filename=u'file.pdf') kwargs['file'] = value if portal_type in ('Image', 'News Item') and 'image' not in kwargs: prefill_image_types(portal, kwargs) id_ = kwargs.pop('id', None) type_ = kwargs.pop('type') content = None if HAS_DEXTERITY: # The title attribute for Dexterity types needs to be unicode if 'title' in kwargs and isinstance(kwargs['title'], str): kwargs['title'] = kwargs['title'].decode('utf-8') from plone.dexterity.interfaces import IDexterityFTI from plone.dexterity.utils import createContentInContainer try: getUtility(IDexterityFTI, name=type_) content = createContentInContainer(container, type_, **create_kwargs) if id_ is not None and content.id != id_: container.manage_renameObject(content.id, id_) except ComponentLookupError: pass if HAS_DEXTERITY and content: # For dexterity-types, we need a second pass to fill all fields # using their widgets to get e.g. RichText-values created # correctly. fti = getUtility(IDexterityFTI, name=type_) schema = fti.lookupSchema() fields = {} for name in schema: fields[name] = schema[name] for schema in getAdditionalSchemata(portal_type=type_): for name in schema: fields[name] = schema[name] for name, field in fields.items(): widget = queryMultiAdapter((field, getRequest()), IFieldWidget) if widget and name in kwargs: if not IFromUnicode.providedBy(field): value = kwargs[name] elif isinstance(kwargs[name], unicode): value = kwargs[name] else: value = unicode(str(kwargs[name]), 'utf-8', errors='ignore') converter = IDataConverter(widget) dm = queryMultiAdapter((content, field), IDataManager) if dm: dm.set(converter.toFieldValue(value)) if content is None: if id_ is None: normalizer = queryUtility(IURLNormalizer) id_ = normalizer.normalize(kwargs['title']) # It must be Archetypes based content: content = container[container.invokeFactory(type_, id_, **kwargs)] content.processForm() return IUUID(content)
def additionalSchemata(self): for behavior in getAdditionalSchemata(portal_type=self.portal_type): yield behavior for behavior in get_default_variant_aspects(self.context): yield behavior
def additionalSchemata(self): return getAdditionalSchemata(context=self.context)
def _get_schemata(self): fti = self.fti yield fti.lookupSchema() for schema in getAdditionalSchemata(portal_type=fti.getId()): yield schema
def get_behaviors_schema(obj): return list(getAdditionalSchemata(obj))