Пример #1
0
    def setDefaults(self, instance):
        """Only call during object initialization. Sets fields to
        schema defaults
        """
        # TODO think about layout/vs dyn defaults
        for field in self.values():
            if field.getName().lower() == 'id':
                continue
            if field.type == "reference":
                continue

            # always set defaults on writable fields
            mutator = field.getMutator(instance)
            if mutator is None:
                continue
            default = field.getDefault(instance)

            args = (default,)
            kw = {'field': field.__name__,
                  '_initializing_': True}
            if shasattr(field, 'default_content_type'):
                # specify a mimetype if the mutator takes a
                # mimetype argument
                # if the schema supplies a default, we honour that,
                # otherwise we use the site property
                default_content_type = field.default_content_type
                if default_content_type is None:
                    default_content_type = getDefaultContentType(instance)
                kw['mimetype'] = default_content_type
            mapply(mutator, *args, **kw)
    def test_ATDocumentDefaultType(self):
        # move portal_properties out of the way. it was not here
        # when we used CMFTestCase and now it fools with the
        # default mimetype tests
        _orignal_pp = self.portal['portal_properties']
        self.portal._delObject('portal_properties', suppress_events=True)
        from Products.CMFCore.utils import _tool_interface_registry
        _marker = object()
        ptool = _tool_interface_registry.pop('portal_properties', _marker)

        self.loginAsPortalOwner()
        # we create a new document:
        self.portal.invokeFactory('DDocument',
                                  id='testdoc',
                                  title='TestDocument')
        obj = self.portal.testdoc
        # its text field should have the site wide default 'text/plain'
        textfield = obj.getField('body')
        self.assertEqual(textfield.getContentType(obj), 'text/html')
        # and so has the teaser field:
        teaserfield = obj.getField('teaser')
        self.assertEqual(teaserfield.getContentType(obj), 'text/html')

        # then we try to change the sitewide default:
        setDefaultContentType(self.portal, "text/x-web-markdown")
        # while this raises no error it won't change the default, as we have
        # no properties tool nor properties sheet
        self.assertEqual(getDefaultContentType(self.portal),
                         'text/x-web-markdown')
        self.portal['portal_properties'] = _orignal_pp
        if ptool is not _marker:
            _tool_interface_registry['portal_properties'] = ptool
    def test_ATDocumentDefaultType(self):
        # move portal_properties out of the way. it was not here
        # when we used CMFTestCase and now it fools with the
        # default mimetype tests
        _orignal_pp = self.portal['portal_properties']
        self.portal._delObject('portal_properties', suppress_events=True)
        from Products.CMFCore.utils import _tool_interface_registry
        _marker = object()
        ptool = _tool_interface_registry.pop('portal_properties', _marker)

        self.loginAsPortalOwner()
        # we create a new document:
        self.portal.invokeFactory(
            'DDocument', id='testdoc', title='TestDocument')
        obj = self.portal.testdoc
        # its text field should have the site wide default 'text/plain'
        textfield = obj.getField('body')
        self.assertEqual(textfield.getContentType(obj), 'text/html')
        # and so has the teaser field:
        teaserfield = obj.getField('teaser')
        self.assertEqual(teaserfield.getContentType(obj), 'text/html')

        # then we try to change the sitewide default:
        setDefaultContentType(self.portal, "text/x-web-markdown")
        # while this raises no error it won't change the default, as we have
        # no properties tool nor properties sheet
        self.assertEqual(getDefaultContentType(
            self.portal), 'text/x-web-markdown')
        self.portal['portal_properties'] = _orignal_pp
        if ptool is not _marker:
            _tool_interface_registry['portal_properties'] = ptool
Пример #4
0
    def setDefaults(self, instance):
        """Only call during object initialization. Sets fields to
        schema defaults
        """
        # TODO think about layout/vs dyn defaults
        for field in self.values():
            if field.getName().lower() == 'id':
                continue
            if field.type == "reference":
                continue

            # always set defaults on writable fields
            mutator = field.getMutator(instance)
            if mutator is None:
                continue
            default = field.getDefault(instance)

            args = (default, )
            kw = {'field': field.__name__, '_initializing_': True}
            if shasattr(field, 'default_content_type'):
                # specify a mimetype if the mutator takes a
                # mimetype argument
                # if the schema supplies a default, we honour that,
                # otherwise we use the site property
                default_content_type = field.default_content_type
                if default_content_type is None:
                    default_content_type = getDefaultContentType(instance)
                kw['mimetype'] = default_content_type
            mapply(mutator, *args, **kw)
def copyField(self, field, translation):
    accessor = field.getEditAccessor(self.context)
    if not accessor:
        accessor = field.getAccessor(self.context)
    if accessor:
        data = accessor()
    else:
        data = field.get(self.context)
    mutator = field.getMutator(translation)
    # if field.__name__ == 'remarks':
    #     import pdb; pdb.set_trace( )
    if mutator is not None:
        # Protect against weird fields, like computed fields
        kw = {}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a
            # mimetype argument
            # if the schema supplies a default, we honour that,
            # otherwise we use the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(field)
            kw['mimetype'] = default_content_type

        mutator(data, **kw)
    else:
        field.set(translation, data)
Пример #6
0
def setDefaults(self, instance):
    """Only call during object initialization, this function sets fields
    to schema defaults.  It's adapted from the original to support
    IAcquireFieldDefaults adapters.  If IAcquireFieldDefaults adapter
    does not find a suitable field, or that field's value is Falseish,
    this function will not continue with the normal default machinery.
    """
    for field in self.values():

        # ## bika addition: we fire adapters for IAcquireFieldDefaults.
        # If IAcquireFieldDefaults returns None, this signifies "ignore" return.
        # First adapter found with non-None result, wins.
        value = None
        if shasattr(field, 'acquire'):
            adapters = {}
            for adapter in getAdapters((instance,), IAcquireFieldDefaults):
                sort_val = getattr(adapter[1], 'sort', 1000)
                if sort_val not in adapters:
                    adapters[sort_val] = []
                adapters[sort_val].append(adapter)
            if adapters:
                keys = sorted(adapters.keys())
                keys.reverse()
                adapter = adapters[keys[0]]
                _value = adapter[0][1](field)
                if _value is not None:
                    value = _value

        if field.getName().lower() == 'id':
            continue

        # If our adapter reflects a value for a reference field, it will
        # be permitted.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default,)
        kw = {'field': field.__name__,
              '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a mimetype argument if
            # the schema supplies a default, we honour that, otherwise we use
            # the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
Пример #7
0
def setDefaults(self, instance):
    """Only call during object initialization, this function sets fields
    to schema defaults.  It's adapted from the original to support
    IAcquireFieldDefaults adapters.  If IAcquireFieldDefaults adapter
    does not find a suitable field, or that field's value is Falseish,
    this function will not continue with the normal default machinery.
    """
    for field in self.values():

        # ## bika addition: we fire adapters for IAcquireFieldDefaults.
        # If IAcquireFieldDefaults returns None, this signifies "ignore" return.
        # First adapter found with non-None result, wins.
        value = None
        if shasattr(field, 'acquire'):
            adapters = {}
            for adapter in getAdapters((instance, ), IAcquireFieldDefaults):
                sort_val = getattr(adapter[1], 'sort', 1000)
                if sort_val not in adapters:
                    adapters[sort_val] = []
                adapters[sort_val].append(adapter)
            if adapters:
                keys = sorted(adapters.keys())
                keys.reverse()
                adapter = adapters[keys[0]]
                _value = adapter[0][1](field)
                if _value is not None:
                    value = _value

        if field.getName().lower() == 'id':
            continue

        # If our adapter reflects a value for a reference field, it will
        # be permitted.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default, )
        kw = {'field': field.__name__, '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a mimetype argument if
            # the schema supplies a default, we honour that, otherwise we use
            # the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
Пример #8
0
def setDefaults(self, instance):
    """Only call during object initialization. Sets fields to
    schema defaults
    """
    # # TODO think about layout/vs dyn defaults
    for field in self.values():

        value = None

        # if analysis request, set sampling date to default to today
        if field.getName().lower() == 'samplingdate' \
                and instance.portal_type == 'AnalysisRequest':
            now = DateTime().strftime("%Y-%m-%d %H:%M")
            value = now

        # From here, the rest of the body of the original function:
        # Products.Archetypes.Schema.BasicSchema#setDefaults

        if field.getName().lower() == 'id':
            continue
        # The original version skipped all reference fields.  I obviously do
        # find some use in defining their defaults anyway, so if our adapter
        # reflects a value for a reference field, I will allow it.
        if field.type == "reference" and not value:
            continue

        default = value if value else field.getDefault(instance)

        # always set defaults on writable fields
        mutator = field.getMutator(instance)
        if mutator is None:
            continue

        args = (default,)
        kw = {'field': field.__name__,
              '_initializing_': True}
        if shasattr(field, 'default_content_type'):
            # specify a mimetype if the mutator takes a
            # mimetype argument
            # if the schema supplies a default, we honour that,
            # otherwise we use the site property
            default_content_type = field.default_content_type
            if default_content_type is None:
                default_content_type = getDefaultContentType(instance)
            kw['mimetype'] = default_content_type

        mapply(mutator, *args, **kw)
Пример #9
0
    def test_ATDocumentDefaultType(self):
        self.loginAsPortalOwner()
        # we create a new document:
        self.portal.invokeFactory('DDocument', id='testdoc', title='TestDocument')
        obj = self.portal.testdoc
        # its text field should have the site wide default 'text/plain'
        textfield = obj.getField('body')
        self.assertEqual(textfield.getContentType(obj), 'text/plain')
        # and so has the teaser field:
        teaserfield = obj.getField('teaser')
        self.assertEqual(teaserfield.getContentType(obj), 'text/plain')

        # then we try to change the sitewide default:
        setDefaultContentType(self.portal, "text/x-web-markdown")
        # while this raises no error it won't change the default, as we have
        # no properties tool nor properties sheet
        self.assertEqual(getDefaultContentType(self.portal), 'text/plain')
Пример #10
0
    def test_ATDocumentDefaultType(self):
        self.loginAsPortalOwner()
        # we create a new document:
        self.portal.invokeFactory('DDocument',
                                  id='testdoc',
                                  title='TestDocument')
        obj = self.portal.testdoc
        # its text field should have the site wide default 'text/plain'
        textfield = obj.getField('body')
        self.assertEqual(textfield.getContentType(obj), 'text/plain')
        # and so has the teaser field:
        teaserfield = obj.getField('teaser')
        self.assertEqual(teaserfield.getContentType(obj), 'text/plain')

        # then we try to change the sitewide default:
        setDefaultContentType(self.portal, "text/x-web-markdown")
        # while this raises no error it won't change the default, as we have
        # no properties tool nor properties sheet
        self.assertEqual(getDefaultContentType(self.portal), 'text/plain')
Пример #11
0
 def get_default_type(self):
     return getDefaultContentType(self.context)
Пример #12
0
    def edit(self, context, field, request):
        """Render widget on edit.

        :returns: Widget's HTML.
        :rtype: string
        """
        from Products.Archetypes.mimetype_utils import getAllowedContentTypes
        from Products.Archetypes.mimetype_utils import getDefaultContentType
        from lxml import etree

        rendered = ''
        allowed_mime_types = getAllowedContentTypes(context)
        if not allowed_mime_types or len(allowed_mime_types) <= 1:
            # Display textarea with default widget
            rendered = self._base(
                **self._base_args(context, field, request)).render()
        else:
            # Let pat-textarea-mimetype-selector choose the widget

            # Initialize the widget without a pattern
            base_args = self._base_args(context, field, request)
            pattern_options = base_args['pattern_options']
            del base_args['pattern']
            del base_args['pattern_options']
            textarea_widget = self._base(None, None, **base_args)
            textarea_widget.klass = ''
            mt_pattern_name = '{}{}'.format(
                self._base._klass_prefix,
                'textareamimetypeselector'
            )

            # Initialize mimetype selector pattern
            value_mime_type = field.getContentType(context)\
                or getDefaultContentType(context)
            mt_select = etree.Element('select')
            mt_select.attrib['id'] = '{}_text_format'.format(field.getName())
            mt_select.attrib['name'] = '{}_text_format'.format(field.getName())
            mt_select.attrib['class'] = mt_pattern_name
            mt_select.attrib['{}{}'.format('data-', mt_pattern_name)] =\
                json.dumps({
                    'textareaName': field.getName(),
                    'widgets': {
                        'text/html': {  # TODO: currently, we only support
                                        # richtext widget config for
                                        # 'text/html', no other mimetypes.
                            'pattern': self.pattern,
                            'patternOptions': pattern_options
                        }
                    }
                })

            # Create a list of allowed mime types
            for mt in allowed_mime_types:
                opt = etree.Element('option')
                opt.attrib['value'] = mt
                if value_mime_type == mt:
                    opt.attrib['selected'] = 'selected'
                opt.text = mt
                mt_select.append(opt)

            # Render the combined widget
            rendered = '{}\n{}'.format(
                textarea_widget.render(),
                etree.tostring(mt_select)
            )
        return rendered