def __call__(self):
        context = aq_inner(self.context)
        fieldname = self.request.get('fieldname')
        portal_type = self.request.get('portal_type')

        fti = zope.component.getUtility(IDexterityFTI, name=portal_type)
        schema = fti.lookupSchema()
        field = schema.get(fieldname)
        if field is None:
            for behaviorname in fti.behaviors:
                behavior = resolve(behaviorname)
                field = behavior.get(fieldname.split('.')[1])
                if field is not None:
                    break
        if IList.providedBy(field) or ISet.providedBy(field):
            vname = field.value_type.vocabularyName
        else:
            vname = field.vocabularyName
        factory = zope.component.getUtility(IVocabularyFactory, vname)
        tree = factory(context)
        leafsOnly = getattr(tree, 'leafsOnly', True)
        
        tree = dict2dynatree(
            self.context,
            tree,
            [],  # selected not needed here, this is done at js side
            leafsOnly,
            False
        )
        return json.dumps(tree)
Beispiel #2
0
 def getFields(self):
     fields = []
     for schema_name, schema in self._getSchemas():
         for field_name, field in getFieldsInOrder(schema):
             if IChoice.providedBy(field):
                 fields.append(StringField(
                     schema_name + '.' + field.__name__,
                     required=field.required,
                     schemata='categorization',
                     widget=atapi.SelectionWidget(
                         label = field.title,
                         description = field.description,
                         ),
                     vocabulary = atapi.DisplayList([(t.value, t.title or t.token) for t in field.vocabulary]),
                     ))
             elif ISet.providedBy(field) and IChoice.providedBy(field.value_type): # XXX should be set
                 fields.append(LinesField(
                     schema_name + '.' + field.__name__,
                     required=field.required,
                     schemata='categorization',
                     widget=atapi.MultiSelectionWidget(
                         label = field.title,
                         description = field.description,
                         ),
                     vocabulary = atapi.DisplayList([(t.value, t.title or t.token) for t in field.value_type.vocabulary]),
                     ))
     return fields
Beispiel #3
0
 def __set__(self, instance, value):
     field = self.__field.bind(instance)
     if ISet.providedBy(field):  # pylint: disable=no-value-for-parameter
         if value is None:
             value = set()
         elif isinstance(value, str):
             value = set(value.split(','))
         value = set(
             map(lambda x: x.id
                 if IPrincipalInfo.providedBy(x) else x, value))
     else:
         value = value.id if IPrincipalInfo.providedBy(value) else value
     field.validate(value)
     if field.readonly:
         raise ValueError("Field {0} is readonly!".format(self.__name))
     protection = IProtectedObject(instance.__parent__, None)
     if not IRoleProtectedObject.providedBy(protection):
         raise ValueError(
             "Can't use role properties on object not providing "
             "IRoleProtectedObject interface!")
     # pylint: disable=assignment-from-no-return
     old_principals = protection.get_principals(self.__role_id)
     if not isinstance(value, set):
         value = {value}
     added = value - old_principals
     removed = old_principals - value
     for principal_id in added:
         protection.grant_role(self.__role_id, principal_id)
     for principal_id in removed:
         protection.revoke_role(self.__role_id, principal_id)
Beispiel #4
0
def migrate_saved_data(ploneformgen, easyform):
    for data_adapter in ploneformgen.objectValues('FormSaveDataAdapter'):
        actions = get_actions(easyform)
        action = actions.get(data_adapter.getId())
        schema = get_schema(easyform)
        if ISaveData.providedBy(action):
            cols = data_adapter.getColumnNames()
            for idx, row in enumerate(data_adapter.getSavedFormInput()):
                if len(row) != len(cols):
                    logger.warning(
                        'Number of columns does not match. Skipping row %s in '
                        'data adapter %s/%s', idx,
                        '/'.join(easyform.getPhysicalPath()),
                        data_adapter.getId())
                    continue
                data = {}
                for key, value in zip(cols, row):
                    field = schema.get(key)
                    value = value.decode('utf8')
                    if IFromUnicode.providedBy(field):
                        value = field.fromUnicode(value)
                    elif IDatetime.providedBy(field) and value:
                        value = DateTime(value).asdatetime()
                    elif IDate.providedBy(field) and value:
                        value = DateTime(value).asdatetime().date()
                    elif ISet.providedBy(field):
                        try:
                            value = set(literal_eval(value))
                        except ValueError:
                            pass
                    elif INamedBlobFileField.providedBy(field):
                        value = None
                    data[key] = value
                action.addDataRow(data)
def handle_field_added(ph_schema, event):
    field = event.field
    index_name = ph_schema.__name__ + '.' + field.__name__
    catalog = getToolByName(getSite(), 'portal_catalog')
    if index_name not in catalog.Indexes:
        if ISet.providedBy(field) and IChoice.providedBy(field.value_type):
            catalog.addIndex(index_name, 'KeywordIndex')
        if IChoice.providedBy(field):
            catalog.addIndex(index_name, 'FieldIndex')
def handle_field_added(ph_schema, event):
    field = event.field
    index_name = ph_schema.__name__ + "." + field.__name__
    catalog = getToolByName(getSite(), "portal_catalog")
    if index_name not in catalog.Indexes:
        if ISet.providedBy(field) and IChoice.providedBy(field.value_type):
            catalog.addIndex(index_name, "KeywordIndex")
        if IChoice.providedBy(field):
            catalog.addIndex(index_name, "FieldIndex")
Beispiel #7
0
def valueToElement(field, value, name=None, force=False):
    """Create and return an element that describes the given value, which is
    assumed to be valid for the given field.

    If name is given, this will be used as the new element name. Otherwise,
    the field's __name__ attribute is consulted.

    If force is True, the value will always be written. Otherwise, it is only
    written if it is not equal to field.missing_value.
    """

    if name is None:
        name = field.__name__

    child = etree.Element(name)

    if value is not None and (force or value != field.missing_value):

        if IDict.providedBy(field):
            key_converter = IToUnicode(field.key_type)
            for k, v in sorted(value.items()):
                list_element = valueToElement(field.value_type, v, 'element',
                                              force)
                list_element.attrib['key'] = key_converter.toUnicode(k)
                child.append(list_element)

        elif ICollection.providedBy(field):
            if ISet.providedBy(field):
                # Serliazation should be consistent even if value was not really a set
                value = sorted(value)
            for v in value:
                list_element = valueToElement(field.value_type, v, 'element',
                                              force)
                child.append(list_element)

        else:
            converter = IToUnicode(field)
            child.text = converter.toUnicode(value)

            # handle i18n
            if isinstance(value, Message):
                child.set(ns('domain', I18N_NAMESPACE), value.domain)
                if not value.default:
                    child.set(ns('translate', I18N_NAMESPACE), '')
                else:
                    child.set(ns('translate', I18N_NAMESPACE), child.text)
                    child.text = converter.toUnicode(value.default)

    return child
 def testImplements(self):
     field = Set()
     self.failUnless(ISet.providedBy(field))
     self.failUnless(IUnorderedCollection.providedBy(field))
     self.failUnless(IAbstractSet.providedBy(field))
     self.failUnless(ICollection.providedBy(field))
Beispiel #9
0
 def testImplements(self):
     field = Set()
     self.assertTrue(ISet.providedBy(field))
     self.assertTrue(IUnorderedCollection.providedBy(field))
     self.assertTrue(IAbstractSet.providedBy(field))
     self.assertTrue(ICollection.providedBy(field))
 def testImplements(self):
     field = Set()
     self.failUnless(ISet.providedBy(field))
     self.failUnless(IUnorderedCollection.providedBy(field))
     self.failUnless(IAbstractSet.providedBy(field))
     self.failUnless(ICollection.providedBy(field))
def get_attribute_values(request, record, attribute_map):
    values = {}
    vocabularies = get_vocabularies(request, attribute_map)

    for header, field in attribute_map.items():

        downloaded = download_field_from_url(field, record[header])
        if downloaded is not False:
            values[field.__name__] = downloaded
            continue

        if IDate.providedBy(field):
            if not record[header]:
                values[field.__name__] = None
            else:
                values[field.__name__] = parse_date(record[header])
            continue

        if IDatetime.providedBy(field):
            if not record[header]:
                values[field.__name__] = None
            else:
                values[field.__name__] = parse_datetime(record[header])
            continue

        if IURI.providedBy(field):
            if not record[header].strip():
                values[field.__name__] = None
                continue

        if IList.providedBy(field):
            if ITextLine.providedBy(field.value_type):
                values[field.__name__] = convert_to_list(record[header])
                continue

        if ISet.providedBy(field):
            if IChoice.providedBy(field.value_type):
                values[field.__name__] = set(convert_to_list(record[header]))
                continue

        if IChoice.providedBy(field):
            if not record[header].strip():
                values[field.__name__] = None
            else:
                vocabulary = vocabularies[header]
                if record[header].lower() not in vocabulary:
                    raise ContentImportError(
                        _(
                            u'The ${name} column contains the '
                            u'unknown value ${value}',
                            mapping=dict(name=header, value=record[header])
                        )
                    )

                values[field.__name__] = vocabulary[record[header].lower()]

            continue

        assert IFromUnicode.providedBy(field), """
            {} does not support fromUnicode
        """.format(field)

        try:
            values[field.__name__] = field.fromUnicode(record[header])

            if isinstance(values[field.__name__], basestring):
                values[field.__name__] = values[field.__name__].strip()
            if isinstance(field, Text):
                values[field.__name__] = values[field.__name__].replace(
                    '<br />', '\n'
                )

        except ValidationError, e:
            raise ContentImportError(e.doc(), colname=header)
        except ValueError, e:
            raise ContentImportError(e.message, colname=header)