Esempio n. 1
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
Esempio n. 2
0
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')
Esempio n. 3
0
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")
Esempio n. 4
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(AjaxSelectWidget, self)._base_args()
        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})
        context = self.context
        field = None

        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if IChoice.providedBy(field):
            args['pattern_options']['allowNewItems'] = 'false'

        args['pattern_options'] = dict_merge(self._ajaxselect_options(),
                                             args['pattern_options'])

        if field and getattr(field, 'vocabulary', None):
            form_url = self.request.getURL()
            source_url = '{0:s}/++widget++{1:s}/@@getSource'.format(
                form_url,
                self.name,
            )
            args['pattern_options']['vocabularyUrl'] = source_url

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            args['pattern_options']['orderable'] = True

        if self.vocabulary == 'plone.app.vocabularies.Keywords':
            membership = getToolByName(context, 'portal_membership')
            user = membership.getAuthenticatedMember()

            registry = getUtility(IRegistry)
            roles_allowed_to_add_keywords = registry.get(
                'plone.roles_allowed_to_add_keywords', set())
            roles = set(user.getRolesInContext(context))
            allowNewItems = bool(
                roles.intersection(roles_allowed_to_add_keywords), )
            args['pattern_options']['allowNewItems'] = str(
                allowNewItems, ).lower()

        return args
Esempio n. 5
0
 def update(self):
     super(AddForm, self).update()
     # set humanized default value for choice fields with no defaults
     for widget in self.widgets:
         field = widget.context
         if IChoice.providedBy(field):
             if IGenenerateVocabularyDefault.providedBy(widget):
                 field.default = widget.getDefaultVocabularyValue()
         if IChoice.providedBy(field) and field.default is None:
             widget._messageNoValue = _("bungeni_widget_no_value",
                                        "choose ${title} ...",
                                        mapping={"title": field.title})
Esempio n. 6
0
 def update(self):
     super(AddForm, self).update()
     # set humanized default value for choice fields with no defaults
     for widget in self.widgets:
         field = widget.context
         if IChoice.providedBy(field):
             if IGenenerateVocabularyDefault.providedBy(widget):
                 field.default = widget.getDefaultVocabularyValue()
         if IChoice.providedBy(field) and field.default is None:
             widget._messageNoValue = _(
                 "bungeni_widget_no_value", "choose ${title} ...", mapping={"title": field.title}
             )
Esempio n. 7
0
 def import_node_for_field(self, field, child):
     value = None
     
     # If we have a collection, we need to look at the value_type.
     # We look for <element>value</element> child nodes and get the
     # value from there
     if ICollection.providedBy(field):
         value_type = field.value_type
         value = []
         for element in child.childNodes:
             if element.nodeName != 'element':
                 continue
             value.append(self.import_node_for_field(value_type, element))
     elif IObject.providedBy(field):
         value = {}
         for element in child.childNodes:
             if element.nodeName != 'property':
                 continue
             property_key = self.extract_text(element.attributes['name'])
             property_value = self.import_node_for_field(field.schema[property_key], element)
             value[property_key] = property_value
     elif IChoice.providedBy(field):
         # Choice fields can be optional, so treat an empty contents as None
         value = self.extract_text(child)
         if not value:
             value = None
         else:
             value = self.from_unicode(field, value)
     else:
         # Otherwise, just get the value of the <property /> node
         value = self.extract_text(child)
         if not (field.getName() == 'root' and value in ['', '/']):
             value = self.from_unicode(field, value)
     value = self.field_typecast(field, value)
     return value
Esempio n. 8
0
    def map_with_vocab(self, behavior, fieldname, value):
        """Look in the schema for a vocab and return the mapped value
        """

        if type(value) == int:
            return str(value)

        portal = self.layer['portal']
        fields = getFieldsInOrder(behavior)
        for name, field in fields:
            if name == fieldname:

                # We have different types of fields, so we have to check,
                # that we become the vocabulary
                value_type = field

                if IList.providedBy(field) or ITuple.providedBy(field):
                    value_type = field.value_type

                if IChoice.providedBy(value_type):
                    if value_type.vocabulary:
                        vocab = value_type.vocabulary(portal)

                    else:
                        vocab = getVocabularyRegistry().get(
                            portal, value_type.vocabularyName)

                    value = vocab.getTerm(value).title

        return value
Esempio n. 9
0
 def __init__(self, field, vocabulary, request):
     # XXX flacoste 2006-07-23 Workaround Zope3 bug #545:
     # CustomWidgetFactory passes wrong arguments to a MultiCheckBoxWidget
     if IChoice.providedBy(vocabulary):
         vocabulary = vocabulary.vocabulary
     MultiCheckBoxWidget.__init__(self, field, vocabulary, request)
     self._disabled_items = []
    def _validate(self, value):
        # XXX HACK: Can't call the super, since it'll check to
        # XXX see if we provide DictRow.
        # We're only a dict, so we can't.
        # super(DictRow, self)._validate(value)

        # Validate the dict against the schema
        # Pass 1 - ensure fields are present
        if value is NO_VALUE:
            return
        # Treat readonly fields
        for field_name in getFields(self.schema).keys():
            field = self.schema[field_name]
            if field.readonly:
                value[field_name] = field.default
        errors = []
        for field_name in getFields(self.schema).keys():
            if field_name not in value:
                errors.append(AttributeNotFoundError(field_name, self.schema))

        if errors:
            raise WrongContainedType(errors, self.__name__)

        # Pass 2 - Ensure fields are valid
        for field_name, field_type in getFields(self.schema).items():
            if IChoice.providedBy(field_type):
                # Choice must be bound before validation otherwise
                # IContextSourceBinder is not iterable in validation
                bound = field_type.bind(value)
                bound.validate(value[field_name])
            else:
                field_type.validate(value[field_name])
Esempio n. 11
0
 def __call__(self):
     # Binding is necessary for named vocabularies
     if IField.providedBy(self.field):
         self.field = self.field.bind(self.context)
     value = self.get_value()
     value_type = self.field.value_type
     if (
         value is not None
         and IChoice.providedBy(value_type)
         and IVocabularyTokenized.providedBy(value_type.vocabulary)
     ):
         values = []
         for v in value:
             try:
                 term = value_type.vocabulary.getTerm(v)
                 values.append({"token": term.token, "title": term.title})
             except LookupError:
                 log.warning(
                     "Term lookup error: %r %s (%s:%s)"
                     % (
                         v,
                         self.field.title,
                         self.context.portal_type,
                         self.context.absolute_url(1),
                     )
                 )
         value = values
     return json_compatible(value)
 def js(self):
     value_type = self.field.value_type
     vocab = None
     if IChoice.providedBy(self.field.value_type):
         if value_type.vocabulary:
             vocab = value_type.vocabulary
         if value_type.vocabularyName:
             vocab = getVocabularyRegistry().get(
                 self.context, self.field.value_type.vocabularyName)
         values = [(term.token, term.value) for term in vocab]
         old_values = self._get_old_values(vocab)
     else:
         values = enumerate(self.context.portal_catalog.uniqueValuesFor('Subject'))
         old_values = enumerate(self.context.Subject())
     tags = ""
     old_tags = ""
     index = 0
     for index, value in values:
         tags += "{id: '%s', name: '%s'}" % (value.replace("'", "\\'"), value.replace("'", "\\'"))
         if values.index((index, value)) < len(values) - 1:
             tags += ", "
     old_index = 0  # XXX: this is not used
     #prepopulate
     for index, value in old_values:
         old_tags += u"{id: '%s', name: '%s'}" % (value.replace("'", "\\'"), value.replace("'", "\\'"))
         if old_values.index((index, value)) < len(old_values) - 1:
             old_tags += ", "
     result = self.js_template % dict(id=self.id,
         klass=self.klass,
         newtags=unicode(tags, errors='ignore'),
         oldtags=old_tags)
     return result
    def _validate(self, value):
        # XXX HACK: Can't call the super, since it'll check to
        # XXX see if we provide DictRow.
        # We're only a dict, so we can't.
        # super(DictRow, self)._validate(value)

        # Validate the dict against the schema
        # Pass 1 - ensure fields are present
        if value is NO_VALUE:
            return
        # Treat readonly fields
        for field_name in getFields(self.schema).keys():
            field = self.schema[field_name]
            if field.readonly:
                value[field_name] = field.default
        errors = []
        for field_name in getFields(self.schema).keys():
            if field_name not in value:
                errors.append(AttributeNotFoundError(field_name, self.schema))

        if errors:
            raise WrongContainedType(errors, self.__name__)

        # Pass 2 - Ensure fields are valid
        for field_name, field_type in getFields(self.schema).items():
            if IChoice.providedBy(field_type):
                # Choice must be bound before validation otherwise
                # IContextSourceBinder is not iterable in validation
                bound = field_type.bind(value)
                bound.validate(value[field_name])
            else:
                field_type.validate(value[field_name])
Esempio n. 14
0
    def map_with_vocab(self, behavior, fieldname, value):
        """Look in the schema for a vocab and return the mapped value
        """

        if type(value) == int:
            return str(value)

        portal = self.layer['portal']
        fields = getFieldsInOrder(behavior)
        for name, field in fields:
            if name == fieldname:

                # We have different types of fields, so we have to check,
                # that we become the vocabulary
                value_type = field

                if IList.providedBy(field) or ITuple.providedBy(field):
                    value_type = field.value_type

                if IChoice.providedBy(value_type):
                    if value_type.vocabulary:
                        vocab = value_type.vocabulary(portal)

                    else:
                        vocab = getVocabularyRegistry().get(
                            portal, value_type.vocabularyName)

                    value = vocab.getTerm(value).title

        return value
Esempio n. 15
0
    def verify_registry_key(self):
        registry = queryUtility(IRegistry)

        if registry is None:
            logger.warning('Plone registry is not available, doing nothing.')
            return False

        record = registry.records.get(self.name)

        if record is None:
            logger.warning(
                'The registry key for the utility registry `%s` is not '
                'registered.', self.name)
            return False

        if not (IList.providedBy(record.field) and
                IChoice.providedBy(record.field.value_type) and
                record.field.value_type.vocabularyName == self.available_vocab
                ):
            logger.warning(
                'The registry key for the utility registry `%s` is registered '
                'incorrectly.', self.name)
            return False

        return True
Esempio n. 16
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value

        args.setdefault('pattern_options', {})
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
        field_name = self.field and self.field.__name__ or None
        args['pattern_options'] = dict_merge(
            get_relateditems_options(self.context, args['value'],
                                     self.separator, self.vocabulary,
                                     self.vocabulary_view, field_name),
            args['pattern_options'])

        return args
Esempio n. 17
0
    def additional(self):
        info = super(ListJsonSchemaProvider, self).additional()
        if IChoice.providedBy(self.field.value_type):
            info['uniqueItems'] = True
        else:
            info['uniqueItems'] = False

        return info
Esempio n. 18
0
    def __init__(self, value_type=None, unique=False, **kw):
        self.search_view = kw.pop('search_view', None)
        self.placeholder = kw.pop('placeholder', '')

        if IChoice.providedBy(value_type):
            self.add_terms = False

        super(Select2MultiField, self).__init__(value_type, unique, **kw)
Esempio n. 19
0
    def additional(self):
        info = super(ListJsonSchemaProvider, self).additional()
        if IChoice.providedBy(self.field.value_type):
            info["uniqueItems"] = True
        else:
            info["uniqueItems"] = False

        return info
Esempio n. 20
0
 def vocabulary_filters(self):
     """The name of the field's vocabulary."""
     choice = IChoice(self.context)
     if choice.vocabulary is None:
         # We need the vocabulary to get the supported filters.
         raise ValueError("The %r.%s interface attribute doesn't have its "
                          "vocabulary specified." %
                          (choice.context, choice.__name__))
     return vocabulary_filters(choice.vocabulary)
Esempio n. 21
0
 def update(self):
     super(AddForm, self).update()
     # set default values for required choice fields
     for widget in self.widgets:
         field = widget.context
         if (IChoice.providedBy(field) and field.required
                 and field.default is None):
             for term in field.vocabulary:
                 field.default = term.value
Esempio n. 22
0
    def update(self):
        super(AddForm, self).update()
        # set default values for required choice fields

        for widget in self.widgets:
            field = widget.context
            if IChoice.providedBy(field) and field.required and field.default is None:
                for term in field.vocabulary:
                    field.default = term.value
Esempio n. 23
0
 def _get_value_type_source(self, field):
     """Get the source of a Choice field that is used as the `value_type`
     for a multi-valued ICollection field, like ITuple.
     """
     value_type = getattr(field, 'value_type', None)
     value_type_source = getattr(value_type, 'source', None)
     if not value_type or not IChoice.providedBy(
             value_type) or not value_type_source:
         return None
     return value_type_source
Esempio n. 24
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})

        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type

        vocabulary_name = self.vocabulary

        field_name = self.field and self.field.__name__ or None

        context = self.context
        view_context = get_widget_form(self)
        # For EditForms and non-Forms (in tests), the vocabulary is looked
        # up on the context, otherwise on the view
        if (IEditForm.providedBy(view_context)
                or not IForm.providedBy(view_context)):
            view_context = context

        args['pattern_options'] = dict_merge(
            get_relateditems_options(
                view_context,
                args['value'],
                self.separator,
                vocabulary_name,
                self.vocabulary_view,
                field_name,
            ), args['pattern_options'])
        if (not self.vocabulary_override and field
                and getattr(field, 'vocabulary', None)):
            # widget vocab takes precedence over field
            form_url = self.request.getURL()
            source_url = '{0:s}/++widget++{1:s}/@@getSource'.format(
                form_url, self.name)
            args['pattern_options']['vocabularyUrl'] = source_url

        return args
Esempio n. 25
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """

        args = super(AjaxSelectWidget, self)._base_args()

        args["name"] = self.name
        args["value"] = self.value

        args.setdefault("pattern_options", {})

        field_name = self.field and self.field.__name__ or None

        context = self.context
        # We need special handling for AddForms
        if IAddForm.providedBy(getattr(self, "form")):
            context = self.form

        vocabulary_name = self.vocabulary
        field = None
        if IChoice.providedBy(self.field):
            args["pattern_options"]["maximumSelectionSize"] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if not vocabulary_name and field is not None:
            vocabulary_name = field.vocabularyName

        args["pattern_options"] = dict_merge(
            get_ajaxselect_options(
                context, args["value"], self.separator, vocabulary_name, self.vocabulary_view, field_name
            ),
            args["pattern_options"],
        )

        if field and getattr(field, "vocabulary", None):
            form_url = self.request.getURL()
            source_url = "%s/++widget++%s/@@getSource" % (form_url, self.name)
            args["pattern_options"]["vocabularyUrl"] = source_url

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            args["pattern_options"]["orderable"] = True

        return args
Esempio n. 26
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """

        args = super(AjaxSelectWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value

        args.setdefault('pattern_options', {})

        field_name = self.field and self.field.__name__ or None

        context = self.context
        # We need special handling for AddForms
        if IAddForm.providedBy(getattr(self, 'form')):
            context = self.form

        vocabulary_name = self.vocabulary
        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if not vocabulary_name and field is not None:
            vocabulary_name = field.vocabularyName

        args['pattern_options'] = dict_merge(
            get_ajaxselect_options(context, args['value'], self.separator,
                                   vocabulary_name, self.vocabulary_view,
                                   field_name),
            args['pattern_options'])

        if field and getattr(field, 'vocabulary', None):
            form_url = self.request.getURL()
            source_url = "%s/++widget++%s/@@getSource" % (form_url, self.name)
            args['pattern_options']['vocabularyUrl'] = source_url

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            args['pattern_options']['orderable'] = True

        return args
Esempio n. 27
0
 def get_widgets(self):
     widgets = form.setUpWidgets(self.form_fields, '', self.context, 
         self.request,ignore_request=True
     )
     for widget in widgets:
         if IChoice.providedBy(widget.context):
             if widget.context.default is None:
                 widget._messageNoValue = _(u"event_form_field_default",
                     default=u"choose ${event_field_title}",
                     mapping={'event_field_title': widget.context.title}
                 )
         yield widget
Esempio n. 28
0
 def get_widgets(self):
     widgets = form.setUpWidgets(self.form_fields, '', self.context, 
         self.request,ignore_request=True
     )
     for widget in widgets:
         if IChoice.providedBy(widget.context):
             if widget.context.default is None:
                 widget._messageNoValue = _(u"event_form_field_default",
                     default=u"choose ${event_field_title}",
                     mapping={'event_field_title': widget.context.title}
                 )
         yield widget
Esempio n. 29
0
def common_widget_updates(context):
    """
    Given a context, update field widgets for it.  Context
    May be any z3c.form instance or a field group contained
    within.
    """
    # form field filter definition:
    vtype = lambda formfield: getattr(formfield.field, 'value_type', None)
    use_vocab = lambda v: hasattr(v, '__len__') and hasattr(v, '__iter__')
    is_choice = lambda formfield: IChoice.providedBy(formfield.field)
    v_choice = lambda formfield: IChoice.providedBy(vtype(formfield))
    is_collection = lambda formfield: ICollection.providedBy(formfield.field)
    is_multi = lambda formfield: is_collection(formfield) and v_choice(
        formfield)  # noqa
    is_date = lambda formfield: IDate.providedBy(formfield.field)
    is_bool = lambda formfield: IBool.providedBy(formfield.field)

    # filtered lists of form fields by type
    formfields = context.fields.values()
    choicefields = filter(is_choice, formfields)
    multifields = filter(is_multi, formfields)
    datefields = filter(is_date, formfields)
    boolfields = filter(is_bool, formfields)

    for formfield in choicefields:
        vocab = formfield.field.vocabulary
        if use_vocab(vocab) and len(vocab) <= 6:
            formfield.widgetFactory = RadioFieldWidget

    for formfield in multifields:
        vocab = formfield.field.value_type.vocabulary
        if use_vocab(vocab) and len(vocab) <= 16:
            formfield.widgetFactory = CheckBoxFieldWidget

    for formfield in datefields:
        formfield.widgetFactory = TypeADateFieldWidget

    for formfield in boolfields:
        formfield.widgetFactory = RadioFieldWidget
Esempio n. 30
0
 def vocabulary_name(self):
     """The name of the field's vocabulary."""
     choice = IChoice(self.context)
     if choice.vocabularyName is None:
         # The webservice that provides the results of the search
         # must be passed in the name of the vocabulary which is looked
         # up by the vocabulary registry.
         raise ValueError(
             "The %r.%s interface attribute doesn't have its "
             "vocabulary specified as a string, so it can't be loaded "
             "by the vocabulary registry." %
             (choice.context, choice.__name__))
     return choice.vocabularyName
Esempio n. 31
0
def common_widget_updates(context):
    """
    Given a context, update field widgets for it.  Context
    May be any z3c.form instance or a field group contained
    within.
    """
    # form field filter definition:
    vtype = lambda formfield: getattr(formfield.field, 'value_type', None)
    use_vocab = lambda v: hasattr(v, '__len__') and hasattr(v, '__iter__')
    is_choice = lambda formfield: IChoice.providedBy(formfield.field)
    v_choice = lambda formfield: IChoice.providedBy(vtype(formfield))
    is_collection = lambda formfield: ICollection.providedBy(formfield.field)
    is_multi = lambda formfield: is_collection(formfield) and v_choice(formfield)  # noqa
    is_date = lambda formfield: IDate.providedBy(formfield.field)
    is_bool = lambda formfield: IBool.providedBy(formfield.field)

    # filtered lists of form fields by type
    formfields = context.fields.values()
    choicefields = filter(is_choice, formfields)
    multifields = filter(is_multi, formfields)
    datefields = filter(is_date, formfields)
    boolfields = filter(is_bool, formfields)

    for formfield in choicefields:
        vocab = formfield.field.vocabulary
        if use_vocab(vocab) and len(vocab) <= 3:
            formfield.widgetFactory = RadioFieldWidget

    for formfield in multifields:
        vocab = formfield.field.value_type.vocabulary
        if use_vocab(vocab) and len(vocab) <= 16:
            formfield.widgetFactory = CheckBoxFieldWidget

    for formfield in datefields:
        formfield.widgetFactory = TypeADateFieldWidget

    for formfield in boolfields:
        formfield.widgetFactory = RadioFieldWidget
Esempio n. 32
0
    def __call__(self, context, request):
        # Sequence widget factory
        if ICollection.providedBy(context):
            args = (context, context.value_type, request) + self.args

        # Vocabulary widget factory
        elif IChoice.providedBy(context):
            args = (context, context.vocabulary, request) + self.args

        # Regular widget factory
        else:
            args = (context, request) + self.args

        return self._create(args)
Esempio n. 33
0
 def __call__(self):
     # Binding is necessary for named vocabularies
     if IField.providedBy(self.field):
         self.field = self.field.bind(self.context)
     value = self.get_value()
     value_type = self.field.value_type
     if (value is not None and IChoice.providedBy(value_type)
             and IVocabularyTokenized.providedBy(value_type.vocabulary)):
         values = []
         for v in value:
             term = value_type.vocabulary.getTerm(v)
             values.append({u"token": term.token, u"title": term.title})
         value = self.field._type(values)
     return json_compatible(value)
Esempio n. 34
0
    def __call__(self, context, request):
        # Sequence widget factory
        if ICollection.providedBy(context):
            args = (context, context.value_type, request) + self.args

        # Vocabulary widget factory
        elif IChoice.providedBy(context):
            args = (context, context.vocabulary, request) + self.args

        # Regular widget factory
        else:
            args = (context, request) + self.args

        return self._create(args)
Esempio n. 35
0
    def update(self):
        super(TaskModifiedTemplate, self).update()

        task = self.context
        ev = self.context0
        request = self.request

        data = {}
        attributes = dict([(attr.interface, list(attr.attributes)) for attr in ev.descriptions])
        for iface, fields in attributes.items():
            ob = iface(task)
            for fieldId in fields:
                field = iface[fieldId].bind(ob)
                value = field.get(ob)

                if IChoice.providedBy(field):
                    try:
                        value = field.vocabulary.getTerm(value).title
                    except LookupError:
                        pass

                if ICollection.providedBy(field) and IChoice.providedBy(field.value_type):
                    voc = field.value_type.vocabulary
                    value = u", ".join([voc.getTerm(v).title for v in value])

                if IDate.providedBy(field):
                    value = getFormatter(request, "date", "full").format(value)

                if IDatetime.providedBy(field):
                    value = getFormatter(request, "dateTime", "medium").format(value)

                data[field.title] = value

        data = data.items()
        data.sort()
        self.data = data
Esempio n. 36
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})

        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type

        vocabulary_name = self.vocabulary
        if not vocabulary_name:
            if field is not None and field.vocabularyName:
                vocabulary_name = field.vocabularyName
            else:
                vocabulary_name = 'plone.app.vocabularies.Catalog'

        field_name = self.field and self.field.__name__ or None
        args['pattern_options'] = dict_merge(
            get_relateditems_options(self.context, args['value'],
                                     self.separator, vocabulary_name,
                                     self.vocabulary_view, field_name),
            args['pattern_options'])

        if not self.vocabulary:  # widget vocab takes precedence over field
            if field and getattr(field, 'vocabulary', None):
                form_url = self.request.getURL()
                source_url = "%s/++widget++%s/@@getSource" % (
                    form_url, self.name)
                args['pattern_options']['vocabularyUrl'] = source_url

        return args
Esempio n. 37
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})

        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type

        vocabulary_name = self.vocabulary
        if not vocabulary_name:
            if field is not None and field.vocabularyName:
                vocabulary_name = field.vocabularyName
            else:
                vocabulary_name = 'plone.app.vocabularies.Catalog'

        field_name = self.field and self.field.__name__ or None
        args['pattern_options'] = dict_merge(
            get_relateditems_options(self.context, args['value'],
                                     self.separator, vocabulary_name,
                                     self.vocabulary_view, field_name),
            args['pattern_options'])

        if not self.vocabulary:  # widget vocab takes precedence over field
            if field and getattr(field, 'vocabulary', None):
                form_url = self.request.getURL()
                source_url = "%s/++widget++%s/@@getSource" % (
                    form_url, self.name)
                args['pattern_options']['vocabularyUrl'] = source_url

        return args
Esempio n. 38
0
 def theme_options(self):
     data = {}
     for name in self.schema.names():
         field = self.schema[name]
         if not IField.providedBy(field):
             continue
         value = getattr(self.settings, name, None)
         if value == None:
             continue
         name = name.replace(self.theme + '_', '', 1)
         if IBool.providedBy(field):
             data[name] = jsbool(value)
         elif IChoice.providedBy(field) or ITextLine.providedBy(field):
             data[name] = '"' + value + '"'
         elif IInt.providedBy(field) or IFloat.providedBy(field):
             data[name] = str(value)
     return data
Esempio n. 39
0
def get_vocabularies(request, attribute_map):
    """ Returns a dictionary containing all (translated) vocabularies used by
    the given attribute map.

    """
    vocabularies = {}
    translate = tools.translator(request)
    for header, field in attribute_map.items():
        if IChoice.providedBy(field):
            vocabulary = zope.component.getUtility(IVocabularyFactory,
                                                   field.vocabularyName)
            vocabulary = vocabulary(None)
            vocabularies[header] = dict([
                (translate(term.title).lower(), term.value)
                for term in vocabulary._terms
            ])

    return vocabularies
Esempio n. 40
0
 def __call__(self):
     # Binding is necessary for named vocabularies
     if IField.providedBy(self.field):
         self.field = self.field.bind(self.context)
     value = self.get_value()
     value_type = self.field.value_type
     if value is not None and IChoice.providedBy(value_type):
         # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
         vocab = getattr(value_type.vocabulary, "vocab", value_type.vocabulary)
         if IVocabularyTokenized.providedBy(vocab):
             values = []
             for v in value:
                 try:
                     term = value_type.vocabulary.getTerm(v)
                     values.append({u"token": term.token, u"title": term.title})
                 except LookupError:
                     logger.warning("Term lookup error: %r" % v)
             value = values
     return json_compatible(value)
Esempio n. 41
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args["name"] = self.name
        args["value"] = self.value
        args.setdefault("pattern_options", {})

        vocabulary_name = self.vocabulary
        field = None
        if IChoice.providedBy(self.field):
            args["pattern_options"]["maximumSelectionSize"] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if field is not None and field.vocabularyName:
            vocabulary_name = field.vocabularyName

        field_name = self.field and self.field.__name__ or None
        args["pattern_options"] = dict_merge(
            get_relateditems_options(
                self.context, args["value"], self.separator, vocabulary_name, self.vocabulary_view, field_name
            ),
            args["pattern_options"],
        )

        if field and getattr(field, "vocabulary", None):
            form_url = self.request.getURL()
            source_url = "%s/++widget++%s/@@getSource" % (form_url, self.name)
            args["pattern_options"]["vocabularyUrl"] = source_url

        return args
    def get_value(self, default=None):
        terms = []
        values = getattr(
            self.field.interface(self.context),
            self.field.__name__,
            default,
        )
        if not values:
            return
        if not IChoice.providedBy(self.field.value_type):
            return

        for value in values:
            term = _get_vocab_term(
                self.context,
                self.field.value_type.vocabularyName,
                value,
            )
            terms.append(term)
        return terms
Esempio n. 43
0
def _validate_fields(schema, value, errors=None):
    if errors is None:
        errors = []
    # Interface can be used as schema property for Object fields that plan to
    # hold values of any type.
    # Because Interface does not include any Attribute, it is obviously not
    # worth looping on its methods and filter them all out.
    if schema is Interface:
        return errors
    # if `value` is part of a cyclic graph, we need to break the cycle to avoid
    # infinite recursion. Collect validated objects in a thread local dict by
    # it's python represenation. A previous version was setting a volatile
    # attribute which didn't work with security proxy
    if id(value) in VALIDATED_VALUES.__dict__:
        return errors
    VALIDATED_VALUES.__dict__[id(value)] = True
    # (If we have gotten here, we know that `value` provides an interface
    # other than zope.interface.Interface;
    # iow, we can rely on the fact that it is an instance
    # that supports attribute assignment.)
    try:
        for name in schema.names(all=True):
            if not IMethod.providedBy(schema[name]):
                try:
                    attribute = schema[name]
                    if IChoice.providedBy(attribute):
                        # Choice must be bound before validation otherwise
                        # IContextSourceBinder is not iterable in validation
                        bound = attribute.bind(value)
                        bound.validate(getattr(value, name))
                    elif IField.providedBy(attribute):
                        # validate attributes that are fields
                        attribute.validate(getattr(value, name))
                except ValidationError as error:
                    errors.append(error)
                except AttributeError as error:
                    # property for the given name is not implemented
                    errors.append(SchemaNotFullyImplemented(error))
    finally:
        del VALIDATED_VALUES.__dict__[id(value)]
    return errors
Esempio n. 44
0
def _validate_fields(schema, value, errors=None):
    if errors is None:
        errors = []
    # Interface can be used as schema property for Object fields that plan to
    # hold values of any type.
    # Because Interface does not include any Attribute, it is obviously not
    # worth looping on its methods and filter them all out.
    if schema is Interface:
        return errors
    # if `value` is part of a cyclic graph, we need to break the cycle to avoid
    # infinite recursion. Collect validated objects in a thread local dict by
    # it's python represenation. A previous version was setting a volatile
    # attribute which didn't work with security proxy
    if id(value) in VALIDATED_VALUES.__dict__:
        return errors
    VALIDATED_VALUES.__dict__[id(value)] = True
    # (If we have gotten here, we know that `value` provides an interface
    # other than zope.interface.Interface;
    # iow, we can rely on the fact that it is an instance
    # that supports attribute assignment.)
    try:
        for name in schema.names(all=True):
            if not IMethod.providedBy(schema[name]):
                try:
                    attribute = schema[name]
                    if IChoice.providedBy(attribute):
                        # Choice must be bound before validation otherwise
                        # IContextSourceBinder is not iterable in validation
                        bound = attribute.bind(value)
                        bound.validate(getattr(value, name))
                    elif IField.providedBy(attribute):
                        # validate attributes that are fields
                        attribute.validate(getattr(value, name))
                except ValidationError as error:
                    errors.append(error)
                except AttributeError as error:
                    # property for the given name is not implemented
                    errors.append(SchemaNotFullyImplemented(error))
    finally:
        del VALIDATED_VALUES.__dict__[id(value)]
    return errors
Esempio n. 45
0
 def get_value(self, default=None):
     values = getattr(
         self.field.interface(self.context),
         self.field.__name__,
         default,
     )
     if not values:
         return values
     elif not IChoice.providedBy(self.field.value_type):
         return values
     return [
         dict(
             title=get_term_title(
                 self.context,
                 self.request,
                 self.field.value_type,
                 value,
             ),
             value=value,
         ) for value in values
     ]
    def get_fieldtype_by_schema(self, field):
        type_field = ""
        if IRelationList.providedBy(field):
            type_field = "relation"
        elif "ListField" in str(field):
            type_field = "datagridfield"
            self.datagrids[field.__name__] = False
        elif IChoice.providedBy(field):
            type_field = "choice"
        elif ITextLine.providedBy(field):
            type_field = "text"
        elif IList.providedBy(field):
            type_field = "list"
        elif IText.providedBy(field):
            type_field = "text"
        elif IRichText.providedBy(field):
            type_field = "text"
        else:
            type_field = "unknown"

        return type_field
    def get_default_value_by_schema(self, field):
        type_field = " "
        if IRelationList.providedBy(field):
            type_field = []
        elif "ListField" in str(field):
            type_field = []
            self.datagrids[field.__name__] = False
        elif IChoice.providedBy(field):
            type_field = " "
        elif ITextLine.providedBy(field):
            type_field = " "
        elif IList.providedBy(field):
            type_field = []
        elif IText.providedBy(field):
            type_field = " "
        elif IRichText.providedBy(field):
            type_field = " "
        else:
            type_field = " "

        return type_field
 def js(self):
     value_type = self.field.value_type
     vocab = None
     if IChoice.providedBy(self.field.value_type):
         if value_type.vocabulary:
             vocab = value_type.vocabulary
         if value_type.vocabularyName:
             vocab = getVocabularyRegistry().get(
                 self.context, self.field.value_type.vocabularyName)
         values = [(term.token, term.value) for term in vocab]
         old_values = self._get_old_values(vocab)
     else:
         values = enumerate(
             self.context.portal_catalog.uniqueValuesFor('Subject'))
         old_values = enumerate(self.context.Subject())
     tags = ""
     old_tags = ""
     index = 0
     for index, value in values:
         tags += "{id: '%s', name: '%s'}" % (value.replace(
             "'", "\\'"), value.replace("'", "\\'"))
         if values.index((index, value)) < len(values) - 1:
             tags += ", "
     old_index = 0  # XXX: this is not used
     #prepopulate
     for index, value in old_values:
         old_tags += u"{id: '%s', name: '%s'}" % (value.replace(
             "'", "\\'"), value.replace("'", "\\'"))
         if old_values.index((index, value)) < len(old_values) - 1:
             old_tags += ", "
     result = self.js_template % dict(id=self.id,
                                      klass=self.klass,
                                      newtags=unicode(tags,
                                                      errors='ignore'),
                                      oldtags=old_tags)
     return result
Esempio n. 49
0
 def __init__(self, field, vocabulary, request):
     # XXX flacoste 2006-07-23 Workaround Zope3 bug #545:
     # CustomWidgetFactory passes wrong arguments to a MultiCheckBoxWidget
     if IChoice.providedBy(vocabulary):
         vocabulary = vocabulary.vocabulary
     MultiCheckBoxWidget.__init__(self, field, vocabulary, request)
Esempio n. 50
0
def elementToValue(field, element, default=_marker):
    """Read the contents of an element that is assumed to represent a value
    allowable by the given field.

    If converter is given, it should be an IToUnicode instance.

    If not, the field will be adapted to this interface to obtain a converter.
    """
    value = default
    if IDict.providedBy(field):
        key_converter = IFromUnicode(field.key_type)
        value = OrderedDict()
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)

            key_text = child.attrib.get('key')
            if key_text is None:
                k = None
            else:
                k = key_converter.fromUnicode(six.text_type(key_text))

            value[k] = elementToValue(field.value_type, child)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    elif ICollection.providedBy(field):
        value = []
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)
            v = elementToValue(field.value_type, child)
            value.append(v)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    elif IChoice.providedBy(field):
        vocabulary = None
        try:
            vcf = getUtility(IVocabularyFactory, field.vocabularyName)
            vocabulary = vcf(None)
        except:
            pass

        if vocabulary and hasattr(vocabulary, 'by_value'):
            try:
                field._type = type(list(vocabulary.by_value.keys())[0])
            except:
                pass

        value = fieldTypecast(field, element.text)

    # Unicode
    else:
        text = element.text
        if text is None:
            value = field.missing_value
        else:
            converter = IFromUnicode(field)
            if isinstance(text, six.binary_type):
                text = text.decode()
            else:
                text = six.text_type(text)
            value = converter.fromUnicode(text)

        # handle i18n
        if isinstance(value, six.string_types) and \
                parseinfo.i18n_domain is not None:
            translate_attr = ns('translate', I18N_NAMESPACE)
            domain_attr = ns('domain', I18N_NAMESPACE)
            msgid = element.attrib.get(translate_attr)
            domain = element.attrib.get(domain_attr, parseinfo.i18n_domain)
            if msgid:
                value = Message(msgid, domain=domain, default=value)
            elif translate_attr in element.attrib:
                value = Message(value, domain=domain)

    return value
Esempio n. 51
0
    def _xlsSheet2folder_(self, request, values, folder):
        # dbg # print "_xlsSheet2folder_(folder=%s)" % folder
        fields = fieldsForFactory(folder.contentFactory, ['objectID'])
        allAttributes = {}
        for interface in implementedBy(folder.contentFactory):
            for i_attrName in interface:
                i_attr = interface[i_attrName]
                if IField.providedBy(i_attr):
                    allAttributes[i_attrName] = i_attr
        matrix = [[]]
        for row_idx, col_idx in sorted(values.keys()):
            v = values[(row_idx, col_idx)]
            if isinstance(v, unicode):
                v = u"%s" % v # v.encode(codepage, 'backslashreplace')
            else:
                v = `v`
            v = u'%s' % v.strip()
            last_row, last_col = len(matrix), len(matrix[-1])
            while last_row <= row_idx:
                matrix.extend([[]])
                last_row = len(matrix)
            while last_col < col_idx:
                matrix[-1].extend([''])
                last_col = len(matrix[-1])
            matrix[-1].extend([v])
        attrNameList = matrix[0]
        attrValMatrix = matrix[1:]
        for attrValVector in attrValMatrix:
            attrDict = {}
            for attrIndex, attrVal in enumerate(attrValVector):
                attrDict[attrNameList[attrIndex]] = attrVal
            # ---------------------------------------
#                    if attrDict.has_key('IntID'):
#                        attrDict.pop('IntID')
            if attrDict.has_key('objectID') and \
               attrDict['objectID'] in folder:
                attrObjectID = attrDict.pop('objectID')
                oldObj = folder[attrObjectID]
                # dbg # print "update old object: ", oldObj.ikName
                for attrName, newValString in attrDict.items():
                    attrField = allAttributes[attrName]
                    if IChoice.providedBy(attrField):
                        v_widget = getMultiAdapter(\
                                        (attrField,request),
                                        interfaces.IFieldWidget)
                        v_widget.context = oldObj
                        v_dataconverter = queryMultiAdapter(\
                                        (attrField, v_widget),
                                        interfaces.IDataConverter)
                        if len(newValString) > 0:
                            try:
                                newVal = v_dataconverter.toFieldValue([newValString])
                            except LookupError:
                                newVal = v_dataconverter.toFieldValue([])
                        else:
                            newVal = v_dataconverter.toFieldValue([])
                    else:
                        if attrName == "isTemplate":
                            v_widget = checkbox.SingleCheckBoxFieldWidget(\
                                        attrField,request)
                        else:
                            v_widget = getMultiAdapter(\
                                            (attrField,request),
                                            interfaces.IFieldWidget)
                        v_widget.context = oldObj
                        v_dataconverter = queryMultiAdapter(\
                                        (attrField, v_widget),
                                        interfaces.IDataConverter)
                        if ICollection.providedBy(attrField):
                            if len(newValString) > 0:
                                newVal = v_dataconverter.toFieldValue(newValString.split(';'))
                            else:
                                newVal = v_dataconverter.toFieldValue([])
                        else:
                            try:
                                newVal = v_dataconverter.toFieldValue(newValString)
                            except LookupError:
                                newVal = getattr(oldObj, attrName)
                    if getattr(oldObj, attrName) != newVal:
                        # dbg # print "change Value  old:'%s'  new:'%s'" % \
                        # dbg #     (getattr(oldObj, attrName), newVal)
                        setattr(oldObj, attrName, newVal)
                        dcore = IWriteZopeDublinCore(oldObj)
                        dcore.modified = datetime.utcnow()
                        if attrName == "ikName":
                            IBrwsOverview(oldObj).setTitle(newVal)
            else:
                oldObj = None
                # new Object
#                        newObj = createObject(self.factoryId)
#                        newObj.__post_init__()
                # dbg # print "new object: ", attrDict['ikName']
                dataVect = {}
                for attrName, newValString in attrDict.items():
                    attrField = allAttributes[attrName]
                    if IChoice.providedBy(attrField):
                        v_widget = getMultiAdapter(\
                                        (attrField,request),
                                        interfaces.IFieldWidget)
                        v_dataconverter = queryMultiAdapter(\
                                        (attrField, v_widget),
                                        interfaces.IDataConverter)
                        if len(newValString) > 0:
                            try:
                                newVal = v_dataconverter.toFieldValue([newValString])
                            except LookupError:
                                newVal = v_dataconverter.toFieldValue([])
                        else:
                            newVal = v_dataconverter.toFieldValue([])
                    else:
                        if attrName == "isTemplate":
                            v_widget = checkbox.SingleCheckBoxFieldWidget(\
                                        attrField,request)
                        else:
                            v_widget = getMultiAdapter(\
                                            (attrField,request),
                                            interfaces.IFieldWidget)
                        v_dataconverter = queryMultiAdapter(\
                                        (attrField, v_widget),
                                        interfaces.IDataConverter)
                        if ICollection.providedBy(attrField):
                            if len(newValString) > 0:
                                try:
                                    newVal = v_dataconverter.toFieldValue(newValString.split(';'))
                                except LookupError:
                                    newVal = v_dataconverter.toFieldValue([])
                            else:
                                newVal = v_dataconverter.toFieldValue([])
                        else:
                            try:
                                newVal = v_dataconverter.toFieldValue(newValString)
                            except LookupError:
                                newVal = None
                    dataVect[str(attrName)] = newVal
                    #setattr(newObj, attrName, newVal)
                #self.context.__setitem__(newObj.objectID, newObj)
                #print "dataVect: ", dataVect
                newObj = folder.contentFactory(**dataVect)
                # new Object, but already have an object id
                if attrDict.has_key('objectID'):
                    newObj.setObjectId(attrDict['objectID'])
                newObj.__post_init__()
                if oldObj is not None:
                    dcore = IWriteZopeDublinCore(oldObj)
                    dcore.modified = datetime.utcnow()
                IBrwsOverview(newObj).setTitle(dataVect['ikName'])
                folder[newObj.objectID] = newObj
                if hasattr(newObj, "store_refs"):
                    newObj.store_refs(**dataVect)
                notify(ObjectCreatedEvent(newObj))
Esempio n. 52
0
def elementToValue(field, element, default=_marker):
    """Read the contents of an element that is assumed to represent a value
    allowable by the given field.

    If converter is given, it should be an IToUnicode instance.

    If not, the field will be adapted to this interface to obtain a converter.
    """
    value = default
    if IDict.providedBy(field):
        key_converter = IFromUnicode(field.key_type)
        value = OrderedDict()
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)

            key_text = child.attrib.get('key')
            if key_text is None:
                k = None
            else:
                k = key_converter.fromUnicode(six.text_type(key_text))

            value[k] = elementToValue(field.value_type, child)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    elif ICollection.providedBy(field):
        value = []
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)
            v = elementToValue(field.value_type, child)
            value.append(v)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    elif IChoice.providedBy(field):
        vocabulary = None
        try:
            vcf = getUtility(IVocabularyFactory, field.vocabularyName)
            vocabulary = vcf(None)
        except:
            pass

        if vocabulary and hasattr(vocabulary, 'by_value'):
            try:
                field._type = type(list(vocabulary.by_value.keys())[0])
            except:
                pass

        value = fieldTypecast(field, element.text)

    # Unicode
    else:
        text = element.text
        if text is None:
            value = field.missing_value
        else:
            converter = IFromUnicode(field)
            if isinstance(text, six.binary_type):
                text = text.decode()
            else:
                text = six.text_type(text)
            value = converter.fromUnicode(text)

        # handle i18n
        if isinstance(value, six.string_types) and \
                parseinfo.i18n_domain is not None:
            translate_attr = ns('translate', I18N_NAMESPACE)
            domain_attr = ns('domain', I18N_NAMESPACE)
            msgid = element.attrib.get(translate_attr)
            domain = element.attrib.get(domain_attr, parseinfo.i18n_domain)
            if msgid:
                value = Message(msgid, domain=domain, default=value)
            elif translate_attr in element.attrib:
                value = Message(value, domain=domain)

    return value
Esempio n. 53
0
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)
Esempio n. 54
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """

        args = super(AjaxSelectWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value

        args.setdefault('pattern_options', {})

        field_name = self.field and self.field.__name__ or None

        context = self.context
        view_context = get_widget_form(self)
        # For EditForms and non-Forms (in tests), the vocabulary is looked
        # up on the context, otherwise on the view
        if (
            IEditForm.providedBy(view_context) or
            not IForm.providedBy(view_context)
        ):
            view_context = context

        vocabulary_name = self.vocabulary
        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if IChoice.providedBy(field):
            args['pattern_options']['allowNewItems'] = 'false'

        args['pattern_options'] = dict_merge(
            get_ajaxselect_options(view_context, args['value'], self.separator,
                                   vocabulary_name, self.vocabulary_view,
                                   field_name),
            args['pattern_options'])

        if field and getattr(field, 'vocabulary', None):
            form_url = self.request.getURL()
            source_url = '{0:s}/++widget++{1:s}/@@getSource'.format(
                form_url,
                self.name
            )
            args['pattern_options']['vocabularyUrl'] = source_url

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            args['pattern_options']['orderable'] = True

        if self.vocabulary == 'plone.app.vocabularies.Keywords':
            membership = getToolByName(context, 'portal_membership')
            user = membership.getAuthenticatedMember()

            registry = getUtility(IRegistry)
            roles_allowed_to_add_keywords = registry.get(
                'plone.roles_allowed_to_add_keywords', [])
            roles = set(user.getRolesInContext(context))

            allowNewItems = 'false'
            if roles.intersection(roles_allowed_to_add_keywords):
                allowNewItems = 'true'
            args['pattern_options']['allowNewItems'] = allowNewItems

        return args
Esempio n. 55
0
 def handleSubmit(self, action):
     """submit was pressed"""
     if 'xlsdata' in self.widgets:
         fields = self.allFields
         codepage = self.widgets['codepage'].value[0]
         fileWidget = self.widgets['xlsdata']
         fileUpload = fileWidget.extract()
         filename = datetime.now().strftime('in_%Y%m%d%H%M%S.xls')
         f_handle, f_name = tempfile.mkstemp(filename)
         outf = open(f_name, 'wb')
         outf.write(fileUpload.read())
         outf.close()
         parseRet = xl.parse_xls(f_name, codepage)
         os.remove(f_name)
         #
         allAttributes = {}
         for interface in implementedBy(self.factory):
             for i_attrName in interface:
                 i_attr = interface[i_attrName]
                 if IField.providedBy(i_attr):
                     allAttributes[i_attrName] = i_attr
         #
         for sheet_name, values in parseRet:
             matrix = [[]]
             for row_idx, col_idx in sorted(values.keys()):
                 v = values[(row_idx, col_idx)]
                 if isinstance(v, unicode):
                     v = u"%s" % v  # v.encode(codepage, 'backslashreplace')
                 else:
                     v = ` v `
                 v = u'%s' % v.strip()
                 last_row, last_col = len(matrix), len(matrix[-1])
                 while last_row <= row_idx:
                     matrix.extend([[]])
                     last_row = len(matrix)
                 while last_col < col_idx:
                     matrix[-1].extend([''])
                     last_col = len(matrix[-1])
                 matrix[-1].extend([v])
             attrNameList = matrix[0]
             attrValMatrix = matrix[1:]
             for attrValVector in attrValMatrix:
                 attrDict = {}
                 for attrIndex, attrVal in enumerate(attrValVector):
                     attrDict[attrNameList[attrIndex]] = attrVal
                 # ---------------------------------------
                 if attrDict.has_key('IntID'):
                     attrDict.pop('IntID')
                 if attrDict.has_key('objectID'):
                     attrObjectID = attrDict.pop('objectID')
                     oldObj = self.context[attrObjectID]
                     for attrName, newValString in attrDict.items():
                         #print u"ddd4-> %s" % (attrName)
                         attrField = allAttributes[attrName]
                         #print u"type(%s): %s" % (attrField, type(attrField))
                         #                            if attrName == "rooms":
                         if IChoice.providedBy(attrField):
                             v_widget = getMultiAdapter(\
                                             (attrField,self.request),
                                             interfaces.IFieldWidget)
                             v_widget.context = oldObj
                             v_dataconverter = queryMultiAdapter(\
                                             (attrField, v_widget),
                                             interfaces.IDataConverter)
                             if len(newValString) > 0:
                                 newVal = v_dataconverter.toFieldValue(
                                     [newValString])
                             else:
                                 newVal = v_dataconverter.toFieldValue([])
                         else:
                             if attrName == "isTemplate":
                                 v_widget = checkbox.SingleCheckBoxFieldWidget(\
                                             attrField,self.request)
                             else:
                                 v_widget = getMultiAdapter(\
                                                 (attrField,self.request),
                                                 interfaces.IFieldWidget)
                             v_widget.context = oldObj
                             v_dataconverter = queryMultiAdapter(\
                                             (attrField, v_widget),
                                             interfaces.IDataConverter)
                             if ICollection.providedBy(attrField):
                                 if len(newValString) > 0:
                                     newVal = v_dataconverter.toFieldValue(
                                         newValString.split(';'))
                                 else:
                                     newVal = v_dataconverter.toFieldValue(
                                         [])
                             else:
                                 newVal = v_dataconverter.toFieldValue(
                                     newValString)
                         if getattr(oldObj, attrName) != newVal:
                             setattr(oldObj, attrName, newVal)
                             dcore = IWriteZopeDublinCore(oldObj)
                             dcore.modified = datetime.utcnow()
                             if attrName == "ikName":
                                 IBrwsOverview(oldObj).setTitle(newVal)
                 else:
                     oldObj = None
                     # new Object
                     #                        newObj = createObject(self.factoryId)
                     #                        newObj.__post_init__()
                     dataVect = {}
                     for attrName, newValString in attrDict.items():
                         attrField = allAttributes[attrName]
                         if IChoice.providedBy(attrField):
                             v_widget = getMultiAdapter(\
                                             (attrField,self.request),
                                             interfaces.IFieldWidget)
                             v_dataconverter = queryMultiAdapter(\
                                             (attrField, v_widget),
                                             interfaces.IDataConverter)
                             if len(newValString) > 0:
                                 newVal = v_dataconverter.toFieldValue(
                                     [newValString])
                             else:
                                 newVal = v_dataconverter.toFieldValue([])
                         else:
                             if attrName == "isTemplate":
                                 v_widget = checkbox.SingleCheckBoxFieldWidget(\
                                             attrField,self.request)
                             else:
                                 v_widget = getMultiAdapter(\
                                                 (attrField,self.request),
                                                 interfaces.IFieldWidget)
                             v_dataconverter = queryMultiAdapter(\
                                             (attrField, v_widget),
                                             interfaces.IDataConverter)
                             if ICollection.providedBy(attrField):
                                 if len(newValString) > 0:
                                     newVal = v_dataconverter.toFieldValue(
                                         newValString.split(';'))
                                 else:
                                     newVal = v_dataconverter.toFieldValue(
                                         [])
                             else:
                                 newVal = v_dataconverter.toFieldValue(
                                     newValString)
                         dataVect[str(attrName)] = newVal
                         #setattr(newObj, attrName, newVal)
                     #self.context.__setitem__(newObj.objectID, newObj)
                     #print "dataVect: ", dataVect
                     newObj = self.factory(**dataVect)
                     newObj.__post_init__()
                     if oldObj is not None:
                         dcore = IWriteZopeDublinCore(oldObj)
                         dcore.modified = datetime.utcnow()
                     IBrwsOverview(newObj).setTitle(dataVect['ikName'])
                     self.context[newObj.objectID] = newObj
                     if hasattr(newObj, "store_refs"):
                         newObj.store_refs(**dataVect)
                     notify(ObjectCreatedEvent(newObj))
     url = absoluteURL(self.context, self.request)
     self.request.response.redirect(url)
Esempio n. 56
0
    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})

        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type

        vocabulary_name = self.vocabulary

        field_name = self.field and self.field.__name__ or None

        context = self.context
        view_context = get_widget_form(self)
        # For EditForms and non-Forms (in tests), the vocabulary is looked
        # up on the context, otherwise on the view
        if (
            IEditForm.providedBy(view_context) or
            not IForm.providedBy(view_context)
        ):
            view_context = context

        args['pattern_options'] = dict_merge(
            get_relateditems_options(
                view_context,
                args['value'],
                self.separator,
                vocabulary_name,
                self.vocabulary_view,
                field_name,
            ),
            args['pattern_options']
        )
        if (
            not self.vocabulary_override and
            field and
            getattr(field, 'vocabulary', None)
        ):
            # widget vocab takes precedence over field
            form_url = self.request.getURL()
            source_url = '{0:s}/++widget++{1:s}/@@getSource'.format(
                form_url,
                self.name
            )
            args['pattern_options']['vocabularyUrl'] = source_url

        return args