def register():
    """ Register custom widgets and content-types
    """
    registerWidget(EEAReferenceBrowserWidget,
        title='EEA Reference Browser',
        description=(('Reference widget that allows you to browse '
                      'or search the portal for objects to refer to.')),
        used_for=('Products.Archetypes.Field.ReferenceField',))

    registerType(EEARefBrowserDemo, PROJECTNAME)
Beispiel #2
0
def register():
    """ Register custom AT widgets
    """
    registerWidget(
        TagsWidget,
        title='EEA Tags',
        description=('A Google+/Facebook like replacement '
                     'for the Plone keywords widget'),
        used_for=('Products.Archetypes.Field.LinesField',)
    )
Beispiel #3
0
def register():
    """ Custom AT registrations
    """
    registerWidget(
        ManagementPlanWidget,
        title="EEA Management Plan Code",
        description=(
            "Renders a HTML selection widget, to" " allow you enter the year and the" " EEA management plan code"
        ),
        used_for=("eea.forms.fields.ManagementPlanField.ManagementPlanField"),
    )

    registerWidget(
        QuickUploadWidget,
        title="EEA Quick Upload",
        description=("Allows you to drag&drop files directly " "from your computer's Desktop"),
    )
Beispiel #4
0
                               'Value': ''})

        return conditions

    def getUnits(self, units=None):
        return (units and "/" in units) and units.split('/') or [units]

    def getHeightUnits(self):
        field = self.bika_setup.Schema()['PatientConditionsHeightUnits']
        return self.getUnits(field.get(self.bika_setup))

    def getWeightUnits(self):
        field = self.bika_setup.Schema()['PatientConditionsWeightUnits']
        return self.getUnits(field.get(self.bika_setup))

    def getWaistUnits(self):
        field = self.bika_setup.Schema()['PatientConditionsWaistUnits']
        return self.getUnits(field.get(self.bika_setup))

    def getConditionValue(self, condition, unit):
        conditions = self.getPatientCondition()
        for cond in conditions:
            if cond['Condition'] == condition \
                and cond['Unit'] == unit:
                return cond['Value']
        return ''

registerWidget(CasePatientConditionWidget,
               title='CasePatientConditionWidget',
               description='Patient Condition information',)
        'other' : 'Other',
        'addother' : True,
        })
    security = ClassSecurityInfo()

    security.declarePublic('process_form')
    def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False):
        """
        if no value or value equals 'other'
        replace it with the optionally entered one
        """
        value = form.get(field.getName(), empty_marker)
        if value is empty_marker:
            return empty_marker
        if not value or value.lower() in ('other', u'other'):
            # XXX is this generic enough?
            other_name = "%s_other" % field.getName()
            value = form.get(other_name, empty_marker)
        if emptyReturnsMarker and value == '':
            return empty_marker
        return value, {}

InitializeClass(ComboWidget)

registerWidget(ComboWidget,
               title='ComboBox',
               description="Select box together with a string field.",
               used_for=('Products.Archetypes.Field.StringField',)
               )
    _properties.update({
        'macro_view' : "formattablename_view",
        'format' : '%T %F %M %P %L %S',
        'formatter' : {},
        'abbr' : {},
        'join_abbr' : '',
        'withURL' : False,
        })
    _format_properties = ['format', 'formatter', 'abbr',
                          'join_abbr', 'withURL']
    
    security = ClassSecurityInfo()

    security.declarePublic('getKwArgs')
    def getKwArgs(self):
        """mapping of all non-empty formatting properties"""
        result = {}
        for property in self._format_properties:
            value = getattr(self, property, None)
            if value:
                result[property] = value
        return result

InitializeClass(FormattableNameWidget)

registerWidget(FormattableNameWidget,
               title='FormattableName',
               description="Renders a formattable name.",
               used_for=('Products.ATExtensions.fields.FormattableNameField',)
               )
Beispiel #7
0
from AccessControl import ClassSecurityInfo
from Products.ATExtensions.widget import RecordsWidget as ATRecordsWidget
from Products.Archetypes.Registry import registerWidget

class RecordsWidget(ATRecordsWidget):
    security = ClassSecurityInfo()
    _properties = ATRecordsWidget._properties.copy()
    _properties.update({
        'macro': "bika_widgets/recordswidget",
        'helper_js': ("bika_widgets/recordswidget.js",),
        'helper_css': ("bika_widgets/recordswidget.css",),
        'allowDelete': True,
    })

registerWidget(RecordsWidget,
               title = 'RecordsWidget',
               description = (''),
               )
Beispiel #8
0
""" Widget
"""
from Products.Archetypes.Registry import registerWidget
from eea.geotags.widget.location import GeotagsWidget

registerWidget(GeotagsWidget,
    title='Geotags Widget',
    description='Geotags widget',
    used_for=(
        'eea.geotags.field.GeotagsStringField',
        'eea.geotags.field.GeotagsLinesField',
    )
)
        if value is empty_marker:
            return empty_marker

        value = value.split('-')

        try:
            value = DateTime(datetime(*map(int, value)))
        except:
            return empty_marker

        return value, {}


registerWidget(
    DateWidget,
    title='Date widget',
    description=('Date widget'),
    used_for=('Products.Archetypes.Field.DateTimeField',)
)


class DatetimeWidget(DateWidget):
    """Date widget for Archetypes."""

    _properties = DateWidget._properties.copy()
    _properties.update({
        'pattern': 'pickadate',
        'pattern_options': {},
    })

    def _base_args(self, context, field, request):
        """Method which will calculate _base class arguments.
Beispiel #10
0
        'macro': "bika_widgets/srtemplateartemplateswidget",
    })

    security = ClassSecurityInfo()

    security.declarePublic('process_form')
    def process_form(self, instance, field, form, empty_marker = None,
        emptyReturnsMarker = False):
        bsc = getToolByName(instance, 'bika_setup_catalog')
        value = []
        service_uids = form.get('uids', None)
        return service_uids, {}

    security.declarePublic('ARTemplates')
    def ARTemplates(self, field, allow_edit = False):
        fieldvalue = getattr(field, field.accessor)()
        view = SRTemplateARTemplatesView(
            self,
            self.REQUEST,
            fieldvalue = fieldvalue,
            allow_edit = allow_edit
        )
        return view.contents_table(table_only = True)


registerWidget(
    SRTemplateARTemplatesWidget,
    title = 'SR Template AR Templates Selector',
    description = ('SR Template AR Templates Selector'),
)
Beispiel #11
0
        """

        # a poor workaround for Plone repeating itself.
        # XXX this is important XXX
        key = field.getName() + "_value"
        if key in instance.REQUEST:
            return instance.REQUEST[key], {}
        value = form.get(field.getName(), empty_marker)

        if not value:
            return value, {}
        if value is empty_marker:
            return empty_marker
        if emptyReturnsMarker and value == "":
            return empty_marker

        # we make sure that empty "value" inputs are saved as "" empty string.
        for i in range(len(value)):
            value[i] = dict(value[i])
            if "value" not in value[i]:
                value[i]["value"] = ""

        instance.REQUEST[key] = value
        return value, {}

    def jsondumps(self, val):
        return json.dumps(val)


registerWidget(RecordsWidget, title="RecordsWidget", description="")
Beispiel #12
0
                "partition": partitions.get(service_uid, "part-1")
            })

            hidden = hidden_services.get(service_uid, "") == "on"
            as_settings.append({"uid": service_uid, "hidden": hidden})

        # set the analysis services settings
        instance.setAnalysisServicesSettings(as_settings)

        # This returns the value for the Analyses Schema Field
        return value, {}

    security.declarePublic("Analyses")

    def Analyses(self, field, allow_edit=False):
        """Render Analyses Listing Table
        """
        instance = getattr(self, "instance", field.aq_parent)
        table = api.get_view("table_ar_template_analyses",
                             context=instance,
                             request=self.REQUEST)
        # Call listing hooks
        table.update()
        table.before_render()
        return table.ajax_contents_table()


registerWidget(ARTemplateAnalysesWidget,
               title="Sample Template Analyses Layout",
               description=("Sample Template Analyses Layout"))
Beispiel #13
0
                     validating=True):
        field_name = field.getName()
        volume = form.get("{}_volume".format(field_name), "")
        unit = form.get("{}_unit".format(field_name), "")
        value = "{} {}".format(volume, unit).strip()

        if value is empty_marker:
            return empty_marker

        if emptyReturnsMarker and value == "":
            return empty_marker

        return value, {}

    def get_unit(self, vocabulary, raw_value):
        unit = api.get_unit(raw_value).strip()
        if unit not in vocabulary.keys():
            return ""
        return unit

    def get_volume(self, raw_value):
        return api.get_leading_number(raw_value).strip()


registerWidget(
    VolumeUnitWidget,
    title="VolumeUnit",
    description=("Renders and input HTML element for volume entry,"
                 "together with a selection list for unit"),
)
Beispiel #14
0
            self.edit_button.get('overlay_handler', ''),
            'overlay_options':
            json.dumps(
                self.edit_button.get(
                    'overlay_options', {
                        'filter':
                        'head>*,#content>*:not(div.configlet),dl.portalMessage.error,dl.portalMessage.info',
                        'formselector': 'form[id$="base-edit"]',
                        'closeselector': '[name="form.button.cancel"]',
                        'width': '70%',
                        'noform': 'close',
                    }))
        }


registerWidget(ReferenceWidget, title='Reference Widget')


class ajaxReferenceWidgetSearch(BrowserView):
    """ Source for jquery combo dropdown box
    """
    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)
        page = self.request['page']
        nr_rows = self.request['rows']
        sord = self.request['sord']
        sidx = self.request['sidx']
        colModel = json.loads(_u(self.request.get('colModel', '[]')))
        discard_empty = json.loads(_c(self.request.get('discard_empty', "[]")))
        rows = []
Beispiel #15
0
##code-section module-header #fill in your manual code here
##/code-section module-header

from zope.interface import implements
from Products.CompoundField.CompoundWidget import CompoundWidget
from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin


class ArrayWidget(CompoundWidget):
    """
    """
    ##code-section class-header #fill in your manual code here
    ##/code-section class-header

    _properties = CompoundWidget._properties.copy()
    _properties.update({
        'macro': 'ArrayWidget',
        ##code-section widget-properties #fill in your manual code here
        ##/code-section widget-properties
    })

    security = ClassSecurityInfo()


registerWidget(ArrayWidget,
               title='ArrayWidget',
               description=('no description given'),
               used_for=('Products.Archetypes.Field.StringField', ))
##code-section module-footer #fill in your manual code here
##/code-section module-footer
Beispiel #16
0
    support this, you must use it on a folderish type (derived from BaseFolder)
    with 'FileAttachment' in the allowed_content_types. Create a BooleanField
    and use this widget. This will display a form at the bottom of your edit
    form (presuming it's the last widget, which it probably ought to be) where
    you can upload images into your content type. The boolean field itself is
    used to select whether an attachment download box should be presented. This
    is similar to the "related items" box in Plone.

    Content editors may also reference the images directly in their body
    text.

    Caveats: In the edit macro, the upload button may steal the default
    enter-key-press in base_edit.
    """

    # Use the base class properties, and add two of our own
    _properties = TypesWidget._properties.copy()
    _properties.update(
        {
            'macro': 'widget_attachmentsmanager',
            'expanded': False,
        }, )


# Register the widget with Archetypes
registerWidget(
    AttachmentsManagerWidget,
    title='Attachments manager widget',
    description=('Renders controls for uploading attachments to documents', ),
    used_for=('Products.Archetypes.Field.BooleanField', ))
Beispiel #17
0
from Products.Archetypes.Widget import StringWidget
from Products.Archetypes.Registry import registerWidget

class CaptchaWidget(StringWidget):
    _properties = StringWidget._properties.copy()
    _properties.update( {'macro' : "captchaField_widget"} )


registerWidget(CaptchaWidget,
               title = 'Captcha widget',
               description= ('Renders captcha image and string input',),
               used_for = ('Products.qPloneCaptchaField.content.CaptchaField',)
              )
        :type default: str, None
        """
        if not form or not uid:
            return default
        values = form.get(key, None)
        if not values or len(values) == 0:
            return default
        value = values[0].get(uid, default)
        if not check_floatable:
            return value
        return api.is_floatable(value) and value or default

    security.declarePublic("AnalysisSpecificationResults")

    def AnalysisSpecificationResults(self, field, allow_edit=False):
        """Render Analyses Specifications Table
        """
        instance = getattr(self, "instance", field.aq_parent)
        table = api.get_view("table_analysis_specifications",
                             context=instance,
                             request=self.REQUEST)
        # Call listing hooks
        table.update()
        table.before_render()
        return table.ajax_contents_table()


registerWidget(AnalysisSpecificationWidget,
               title="Analysis Specification Results",
               description=("Analysis Specification Results"))
# This file is part of Bika LIMS
#
# Copyright 2011-2016 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.

from AccessControl import ClassSecurityInfo
from Products.ATExtensions.widget import RecordWidget
from Products.Archetypes.Registry import registerWidget
import datetime

class DurationWidget(RecordWidget):
    security = ClassSecurityInfo()
    _properties = RecordWidget._properties.copy()
    _properties.update({
        'macro': "bika_widgets/durationwidget",
    })

registerWidget(DurationWidget,
               title = 'DurationWidget',
               description = (''),
               )
Beispiel #20
0
# Copyright 2018-2019 by it's authors.
# Some rights reserved, see README and LICENSE.

from Products.Archetypes.Widget import IntegerWidget as _i
from Products.Archetypes.Registry import registerPropertyType
from Products.Archetypes.Registry import registerWidget

from AccessControl import ClassSecurityInfo

_marker = []


class IntegerWidget(_i):
    _properties = _i._properties.copy()
    _properties.update({
        'macro': "bika_widgets/integer",
        'unit': '',
    })

    security = ClassSecurityInfo()


registerWidget(
    IntegerWidget,
    title='Integer',
    description=('Renders a HTML text input box which '
                 'accepts a integer value'),
)

registerPropertyType('unit', 'string', IntegerWidget)
"""
Defines ImageInnerContentWidget
"""

__docformat__ = 'restructuredtext'

# Zope imports
from AccessControl import ClassSecurityInfo

# Archetypes imports
from Products.Archetypes.Registry import registerWidget

# Products imports
from Products.PloneArticle.widget import BaseInnerContentWidget

class ImageInnerContentWidget(BaseInnerContentWidget):
    """"""
    
    _properties = BaseInnerContentWidget._properties.copy()
    _properties.update({
        'macro' : "pa_imageinnercontentwidget",
        })

    security = ClassSecurityInfo()
    
registerWidget(ImageInnerContentWidget,
               title='ImageInnerContent',
               description=(''),
               used_for=('Products.PloneArticle.field.imageinnercontent.ImageInnerContentField',)
               )
Beispiel #22
0
                for uid in service_uids:
                    hidden = hiddenans.get(uid, "")
                    hidden = True if hidden == "on" else False
                    outs.append({"uid": uid, "hidden": hidden})
            instance.setAnalysisServicesSettings(outs)

        return service_uids, {}

    security.declarePublic("Analyses")

    def Analyses(self, field, allow_edit=False):
        """ Print analyses table
        """
        fieldvalue = getattr(field, field.accessor)()

        # N.B. we do not want to pass the field as the context to
        # AnalysisProfileAnalysesView, but rather the holding instance
        instance = getattr(self, "instance", field.aq_parent)
        view = AnalysisProfileAnalysesView(instance,
                                           self.REQUEST,
                                           fieldvalue=fieldvalue,
                                           allow_edit=allow_edit)
        return view.contents_table(table_only=True)


registerWidget(
    AnalysisProfileAnalysesWidget,
    title='Analysis Profile Analyses selector',
    description=('Analysis Profile Analyses selector'),
)
class SelectDescriptionWidget(SelectionWidget):
    # Vocabulary= function should return extra descriptions when
    # called with 'extended=True'
    security = ClassSecurityInfo()

    _properties = SelectionWidget._properties.copy()
    _properties.update({
        'macro': 'selectdescription',
        'format': 'select',
        })


registerWidget(SelectDescriptionWidget,
               title='Select with Description',
               description="Select field which uses javascript to control an extended descriptin.",
               used_for=('Products.Archetypes.public.StringField',
                         'Products.Archetypes.Field.LinesField')
               )

# Javascript
JQUERY_ONLOAD = '''\
(function($) { $(function() {
%s
});})(jQuery);
'''
class ManageDescription(BrowserView):
     
    def __call__(self, field, context):
        """render javascript"""            
        return JQUERY_ONLOAD % self.renderJS(field, context)
                fn + "_repeatunit"] or None
            repeatPeriod = fn + "_repeatperiodselected" in form and form[
                fn + "_repeatperiodselected"] or None
            repeatEnabled = (repeatUnit and fn + "_repeatenabled" in form
                             and form[fn + "_repeatenabled"]
                             == 'on') and True or False
            repeatUntil = fn + "_repeatuntil" in form and form[
                fn + "_repeatuntil"] or None
            repeatUntilEnabled = (
                repeatUntil and fn + "_repeatuntilenabled" in form
                and form[fn + "_repeatuntilenabled"] == 'on') and True or False

            value.append({
                'fromenabled': fromEnabled,
                'fromdate': fromDate,
                'repeatenabled': repeatEnabled,
                'repeatunit': repeatUnit,
                'repeatperiod': repeatPeriod,
                'repeatuntilenabled': repeatUntilEnabled,
                'repeatuntil': repeatUntil
            })

        return value, {}


registerWidget(
    ScheduleInputWidget,
    title='ScheduleInputWidget',
    description=('Control for scheduling'),
)
        form[fname] = res # stick it back in request.form
        return res, {}


# TODO: multi inheritance is nasty, when it comes to overriding methods. then
#       there is no clearly defined method resolution order.
class DateWidget(base.AbstractDateWidget, AbstractATDattimeWidget):
    """ Date widget.

    Please note: Archetypes DateTimeFields's values are Zope DateTime
    instances.

    """
registerWidget(DateWidget,
               title='Date widget',
               description=('Date widget'),
               used_for=('Products.Archetypes.Field.DateTimeField',)
               )


class DatetimeWidget(base.AbstractDatetimeWidget, AbstractATDattimeWidget):
    """ DateTime widget """
    _properties = DateWidget._properties.copy()
    _properties.update({
        'macro': 'datetime_input',
    })
registerWidget(DatetimeWidget,
               title='Datetime widget',
               description=('Datetime widget'),
               used_for=('Products.Archetypes.Field.DateTimeField',)
               )
            })
        return outvalues, {}

    def jsondumps(self, val):
        return json.dumps(val)

    def getPatientsGender(self):
        patient = self.aq_parent
        return IPatient.providedBy(patient) and patient.getGender() or "dk"

    def getMenstrualStatus(self):

        statuses = [{
            'Hysterectomy': False,
            'HysterectomyYear': '',
            'OvariesRemoved': False,
            'OvariesRemovedNum': 0,
            'OvariesRemovedYear': ''
        }]

        return len(self.aq_parent.getMenstrualStatus()) > 0 \
                    and self.aq_parent.getMenstrualStatus() \
                    or statuses


registerWidget(
    PatientMenstrualStatusWidget,
    title='PatientMenstrualStatusWidget',
    description='Menstrual status information',
)
from Products.Archetypes.public import StringWidget
from Products.Archetypes.public import LinesWidget
from Products.Archetypes.Registry import registerWidget

class LatLngWidget(StringWidget):
    _properties = StringWidget._properties.copy()
    _properties.update({
        'macro' : "latlng_widget",
        })
    security = ClassSecurityInfo()

#InitializeClass(LatLngWidget)

registerWidget(LatLngWidget,
               title='LatLng',
               description="Renders latitude and longitude fields.",
               used_for=('Products.ATGoogleMaps.field.LatLngField',)
               )

class PolylineWidget(LinesWidget):
    _properties = LinesWidget._properties.copy()
    _properties.update({
        'macro' : "polyline_widget",
        })
    security = ClassSecurityInfo()

#InitializeClass(PolylineWidget)

registerWidget(PolylineWidget,
               title='Polyline',
               description="Renders polyline fields.",
Beispiel #28
0
        [a.sort() for a in groupedIndexes.values()]

        config['groupedIndexes'] = groupedIndexes
        return config

    def SearchResults(self, request, context, accessor):
        """search results"""

        options = dict(original_context=context)
        res = getMultiAdapter((accessor(), request),
                              name='display_query_results')
        return res(**options)


registerWidget(QueryWidget,
               title='Query',
               description=('Field for storing a query'))


class WidgetTraverse(_WidgetTraverse):
    def getConfig(self):
        """get the config"""
        registry = getUtility(IRegistry)
        # First grab the base config, so we can use the operations
        registryreader = IQuerystringRegistryReader(registry)
        registryreader.prefix = "plone.app.querystring.operation"
        op_config = registryreader.parseRegistry()
        # Then combine our fields
        registryreader = IQuerystringRegistryReader(registry)
        registryreader.prefix = "bika.lims.bika_catalog_query"
        config = registryreader.parseRegistry()
Beispiel #29
0
        # Return a dict with the options defined in the schema whose widget needs an edit button.
        return {
            'visible': self.edit_button.get('visible', False),
            'url': self.edit_button.get('url'),
            'return_fields': json.dumps(self.edit_button.get('return_fields')),
            'js_controllers': json.dumps(self.edit_button.get('js_controllers',[])),
            'overlay_handler': self.edit_button.get('overlay_handler', ''),
            'overlay_options': json.dumps(self.edit_button.get('overlay_options',{
                'filter': 'head>*,#content>*:not(div.configlet),dl.portalMessage.error,dl.portalMessage.info',
                'formselector': 'form[id$="base-edit"]',
                'closeselector': '[name="form.button.cancel"]',
                'width': '70%',
                'noform': 'close',}))
            }

registerWidget(ReferenceWidget, title='Reference Widget')

class ajaxReferenceWidgetSearch(BrowserView):

    """ Source for jquery combo dropdown box
    """

    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)
        page = self.request['page']
        nr_rows = self.request['rows']
        sord = self.request['sord']
        sidx = self.request['sidx']
        colModel = json.loads(_u(self.request.get('colModel', '[]')))
        discard_empty = json.loads(_c(self.request.get('discard_empty', "[]")))
        rows = []
from Products.Archetypes import Widget
from Products.Archetypes.Registry import registerWidget
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.ZCatalog.CatalogBrains import AbstractCatalogBrain
from slc.treecategories.interfaces import IInlineTreeView
from zope.component import getMultiAdapter
from zope.interface import implements

class InlineTreeWidget(Widget.InAndOutWidget):
    _properties = Widget.InAndOutWidget._properties.copy()
    _properties.update({'macro' : 'at_widget_inlinetree'})

registerWidget(InlineTreeWidget,
               title='Inline Tree',
               description=('Renders a widget with selected items '
                            'Allows selection of more items via pop up'),
               used_for=('Products.Archetypes.Field.LinesField',)
               )

def getInlineTreeView(context, brain, request, field):
    retval = getMultiAdapter((context, request), name='slc.treecategories.inlinetreeview')
    retval.brain = brain
    #Oh man, could have kept the code as it was...
    retval.realob = brain.getObject()
    retval.context_url = brain.getURL()
    retval._field = field
    return retval

class InlineTreeView(BrowserView):
    implements(IInlineTreeView)
Beispiel #31
0

class RejectionSetupWidget(TypesWidget):
    _properties = TypesWidget._properties.copy()
    _properties.update({
        'macro':
        "bika_widgets/rejectionsetupwidget",
        'helper_js': ("bika_widgets/rejectionsetupwidget.js", ),
        'helper_css': ("bika_widgets/rejectionsetupwidget.css", ),
    })

    security = ClassSecurityInfo()

    def getSortKeys(self, keys):
        # return the option's keys in sorted in order to obtain a sorted set of
        # options.
        # checkbox object isn't an option
        if 'checkbox' in keys:
            keys.remove('checkbox')
        if len(keys) == 0:
            # Doing that in order to get one blank textfield
            keys = ['blank']
        return sorted(keys)


registerWidget(
    RejectionSetupWidget,
    title="Setup's Rejection Widget",
    description=('Widget to define the rejection reasons'),
)
Beispiel #32
0
        """Return a list of services with specs in a category
        """
        bsc = getToolByName(self, 'bika_setup_catalog')
        services = []
        for spec in field.getResultsRange():
            service = bsc(portal_type='AnalysisService',
                          getKeyword=spec['keyword'])[0]
            if service.getCategoryTitle == category_title:
                services.append(spec)
        return services

    security.declarePublic('getCategoryUID')

    def getCategoryUID(self, category_title):
        bsc = getToolByName(self, 'bika_setup_catalog')
        cats = bsc(portal_type="AnalysisCategory")
        cats = [cat.UID for cat in cats if cat.title == category_title]
        if cats:
            return cats[0]
        else:
            return ""


registerWidget(
    SpecWidget,
    title='Analysis Services',
    description=('AnalysisSpec selector.'),
)

#registerPropertyType('default_search_index', 'string', AnalysisSpecsWidget)
Beispiel #33
0
        'popup_name' : 'mars_refpopup',
    })

class MarscatWidget(BReferenceBrowserWidget):
    _properties = BReferenceBrowserWidget._properties.copy()
    _properties.update({
        'macro': 'marscats4browser',
        'image_portal_types':['Image',],
        'image_method':'image_thumb',  
        'popup_name' : 'mars_catpopup',
        'restrict_browsing_to_startup_directory': True,
        })

registerWidget(MarscatWidget,
    title='Mars Categories Browser',
    description=('Reference widget that allows you to browse or'
                 'search the portal for categories to refer to.'),
    used_for=('Products.marscats.Field.MarscatField',)
    )



registerWidget(ReferenceBrowserWidget,
           title='Reference Browser',
               description=('Reference widget that allows you to browse or '
                            'search the portal for objects to refer to.'),
               used_for=('Products.Archetypes.Field.ReferenceField',)
               ) 


Beispiel #34
0
            'MenstrualCycleType': MENSTRUAL_STATUSES.keys()[0],
            'Pregnant': False,
            'MonthOfPregnancy': 0,
            'Hysterectomy': False,
            'HysterectomyYear': '',
            'OvariesRemoved': False,
            'OvariesRemovedNum': 0,
            'OvariesRemovedYear': ''
        }

        # Fill with patient's Menstrual status info
        patient = self.aq_parent.Schema()['Patient'].get(self.aq_parent)
        if patient:
            pms = self.aq_parent.Schema()['MenstrualStatus'].get(
                self.aq_parent)
            if pms:
                statuses = dict(statuses.items() + pms[0].items())

        cms = self.aq_parent.Schema()['MenstrualStatus'].get(self.aq_parent)
        if cms:
            statuses = dict(statuses.items() + cms[0].items())

        return [statuses]


registerWidget(
    CaseMenstrualStatusWidget,
    title='CaseMenstrualStatusWidget',
    description='Menstrual status information',
)
Beispiel #35
0
from Products.Archetypes.Widget import StringWidget
from Products.Archetypes.Registry import registerWidget

CAPTCHA_MACRO = "captchaField_widget"

class CaptchaWidget(StringWidget):
    _properties = StringWidget._properties.copy()
    _properties.update( {'macro' : CAPTCHA_MACRO} )


registerWidget(CaptchaWidget,
               title = 'Captcha widget',
               description= ('Renders captcha image and string input',),
               used_for = ('quintagroup.pfg.captcha.field.CaptchaField',)
              )
        as_settings = []
        for service in services:
            service_uid = api.get_uid(service)
            hidden = hidden_services.get(service_uid, "") == "on"
            as_settings.append({"uid": service_uid, "hidden": hidden})

        # set the analysis services settings
        instance.setAnalysisServicesSettings(as_settings)

        return map(api.get_uid, services), {}

    security.declarePublic("Analyses")

    def Analyses(self, field, allow_edit=False):
        """Render Analyses Listing Table
        """
        instance = getattr(self, "instance", field.aq_parent)
        table = api.get_view("table_analysis_profile_analyses",
                             context=instance,
                             request=self.REQUEST)
        # Call listing hooks
        table.update()
        table.before_render()
        return table.ajax_contents_table()


registerWidget(AnalysisProfileAnalysesWidget,
               title="Analysis Profile Analyses selector",
               description=("Analysis Profile Analyses selector"),)
        'default_protocol' : 'http',
        })
    security = ClassSecurityInfo()
    
    security.declarePublic('process_form')
    def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False):
        """
        add the default protocol to the url field if there is none
        """
        value = form.get(field.getName(), empty_marker)
        if value is empty_marker:
            return empty_marker
        if emptyReturnsMarker and value in ('', {}):
            return empty_marker
        url = value.get('url', None)
        if url and '://' not in url:
            url = self.default_protocol + '://' + url
            value.url = url
        return value, {}

InitializeClass(LabeledUrlWidget)

registerWidget(LabeledUrlWidget,
               title='LabeledUrl',
               description="Renders a URL in an anchor tag "
               "using label as display text.",
               used_for=('Products.ATExtensions.fields.LabeledUrlField',)
               )
registerPropertyType('default_protocol', 'string', LabeledUrlWidget)
Beispiel #38
0
        """
        Returns the expected value saved in the action list object.
        :set_idx: it is an integer with the position of the reflex rules set
        in the widget's list.
        :row_idx: is an integer with the numer of the row from the set
        :element: a string with the name of the element of the action to
            obtain: 'analysisservice', 'cond_row_idx', 'range0', 'range1',
                    'discreteresult', and_or
        """
        if isinstance(set_idx, str):
            set_idx = int(set_idx)
        if isinstance(row_idx, str):
            row_idx = int(row_idx)
        cond = self.getReflexRuleElement(idx=set_idx, element='conditions')
        return cond[row_idx].get(element, '')

    def getAnalysts(self):
        """
        This function returns a displaylist with the available analysts
        """
        analysts = getUsers(self, ['Manager', 'LabManager', 'Analyst'])
        return analysts.sortedByKey()


registerWidget(
    ReflexTestingRulesWidget,
    title="Reflex Rule Widget",
    description=(
        'Widget to define different actions for an analysis services result'),
)
        'macro': "bika_widgets/srtemplateartemplateswidget",
    })

    security = ClassSecurityInfo()

    security.declarePublic('process_form')
    def process_form(self, instance, field, form, empty_marker = None,
        emptyReturnsMarker = False):
        bsc = getToolByName(instance, 'bika_setup_catalog')
        value = []
        service_uids = form.get('uids', None)
        return service_uids, {}

    security.declarePublic('ARTemplates')
    def ARTemplates(self, field, allow_edit = False):
        fieldvalue = getattr(field, field.accessor)()
        view = SRTemplateARTemplatesView(
            self,
            self.REQUEST,
            fieldvalue = fieldvalue,
            allow_edit = allow_edit
        )
        return view.contents_table(table_only = True)


registerWidget(
    SRTemplateARTemplatesWidget,
    title = 'SR Template AR Templates Selector',
    description = ('SR Template AR Templates Selector'),
)
Beispiel #40
0
from Products.Archetypes.Registry import registerPropertyType
from bika.lims.browser import ulocalized_time as ut


class DateTimeWidget(TypesWidget):
    _properties = TypesWidget._properties.copy()
    _properties.update({
        'show_time': False,
        'macro': "bika_widgets/datetimewidget",
        'helper_js': ("bika_widgets/datetimewidget.js", ),
        'helper_css': ("bika_widgets/datetimewidget.css", ),
    })

    security = ClassSecurityInfo()

    def ulocalized_time(self, time, context, request):
        val = ut(time,
                 long_format=self._properties['show_time'],
                 time_only=False,
                 context=context,
                 request=request)
        return val


registerWidget(
    DateTimeWidget,
    title='DateTimeWidget',
    description=('Simple text field, with a jquery date widget attached.'))

registerPropertyType('show_time', 'boolean')
        if 'service' in form:
            for uid, service in form['service'][0].items():
                try:
                    float(form['result'][0][uid])
                    float(form['min'][0][uid])
                    float(form['max'][0][uid])
                except:
                    continue
                value.append({'uid':uid,
                              'result':form['result'][0][uid],
                              'min':form['min'][0][uid],
                              'max':form['max'][0][uid]})
        return value, {}

    security.declarePublic('ReferenceResults')
    def ReferenceResults(self, field, allow_edit = False):
        """ Prints a bika listing with categorized services.
            field contains the archetypes field with a list of services in it
        """
        fieldvalue = getattr(field, field.accessor)()
        view = TableRenderShim(self,
                               self.REQUEST,
                               fieldvalue = fieldvalue,
                               allow_edit = allow_edit)
        return view()

registerWidget(ReferenceResultsWidget,
               title = 'Reference definition results',
               description = ('Reference definition results.'),
               )
Beispiel #42
0
# -*- coding: utf-8 -*-
#
# This file is part of Bika LIMS
#
# Copyright 2011-2017 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.

from Products.Archetypes.Widget import SelectionWidget as _s
from Products.Archetypes.Registry import registerWidget

from AccessControl import ClassSecurityInfo


class SelectionWidget(_s):
    _properties = _s._properties.copy()
    _properties.update({
        'macro': "bika_widgets/selection",
    })

    security = ClassSecurityInfo()


registerWidget(SelectionWidget)
    
    def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False):
        """
        collect form values into a dictionnary suitable for field
        """

        fieldName = field.getName()
        value = form.get(fieldName + '_ref_uids', [])
        
        kwargs = {}

        # form record are not dictionnaries, we must create a real one
        kwargs['search_criterias'] = {}
        kwargs['search_criterias'].update(
            form.get(fieldName + '_search_criterias', {})
            )

        kwargs['uids_found'] = form.get(fieldName + '_uids_found', [])
        kwargs['auto_reference'] = form.get(fieldName + '_auto_reference',
                                            False)

        return value, kwargs
            
    
registerWidget(SmartListWidget,
               title='SmartList',
               description=(''),
               used_for=('Products.PloneArticle.field.smartlistfield.SmartListField',)
               )
Beispiel #44
0
                                  'partition':Partitions[service_uid]})

        if instance.portal_type == 'ARTemplate':
            # Hidden analyses?
            outs = []
            hiddenans = form.get('Hidden', {})
            if service_uids:
                for uid in service_uids:
                    hidden = hiddenans.get(uid, '')
                    hidden = True if hidden == 'on' else False
                    outs.append({'uid':uid, 'hidden':hidden})
            instance.setAnalysisServicesSettings(outs)

        return value, {}

    security.declarePublic('Analyses')
    def Analyses(self, field, allow_edit = False):
        """ Print analyses table
        """
        fieldvalue = getattr(field, field.accessor)()
        view = ARTemplateAnalysesView(self,
                                      self.REQUEST,
                                      fieldvalue = fieldvalue,
                                      allow_edit = allow_edit)
        return view.contents_table(table_only = True)

registerWidget(ARTemplateAnalysesWidget,
               title = 'AR Template Analyses Layout',
               description = ('AR Template Analyses Layout'),
               )
##        def match_handler(mo):
##            g = mo.group
##            return '="' + (g(1) or '') + (g(2) or '') + '__WIDGET_INDEX_MARKER__' + (g(4) or '') + (g(5) or '') + '"'

        #html = FIELD_NAME_INDEX_REGEX.sub(match_handler, html, 0)

        html = html.replace('%s000' % config.ARRAY_FIELDNAME_SEPARATOR,
                            '%s__WIDGET_INDEX_MARKER__' % config.ARRAY_FIELDNAME_SEPARATOR)

        return html

    def splitArrayFieldName(self, field_name):
        # Split an array field name in name part and index part.
        # We split at the last ARRAY_FIELDNAME_SEPARATOR.
        split_point = field_name.rfind(config.ARRAY_FIELDNAME_SEPARATOR)
        fname = field_name[0:split_point]
        index = field_name[split_point+1:]
        return (fname, index)


registerWidget(EnhancedArrayWidget,
               title='EnhancedArrayWidget',
               description=('no description given'),
               used_for=('Products.Archetypes.Field.StringField',)
               )
##code-section module-footer #fill in your manual code here
##/code-section module-footer



        # The widget always returns a empty item (strange) when we use the 
        # multival option.
        # Remove the empty items manually
        if type(value) is types.ListType:
            value = [item for item in value if item]
        return value, kwargs

    security.declarePublic('getGroupId')
    def getGroupId(self, instance):
        groupid = self.groupName
        try:
            translator = IGenericGroupTranslation(instance)
        except ComponentLookupError:
            pass
        except TypeError, e:
            if e[0] == 'Could not adapt':
                pass
            else:
                raise
        else:
            groupid = translator.translateToRealGroupId(self.groupName)
        return groupid


registerWidget(
    UserAndGroupSelectionWidget,
    title='User and Group Selection Widget',
    description=('You can select users searched from a popup window.'),
    used_for=('Products.Archetypes.Field.LinesField',
              'Products.Archetypes.Field.StringField', ))
        result = find(tree)
        if result is None:
             return u'NOT FOUND'
        return result

    security.declarePublic('process_form')
    def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False, validating=True):
        """get values from form field"""
        value = form.get(field.getName(), empty_marker)
        if value is empty_marker:
            return empty_marker
        if emptyReturnsMarker and value == '':
            return empty_marker
        if value == '()':
            return empty_marker
        value = value.strip("|")
        if self.selectMode > 1:
            value = [_ for _ in value.split('|') if _.strip()]
            if not value:
                return empty_marker
        return value, {}

registerWidget(DynatreeWidget,
               title='Dynatree',
               description=('Renders a tree with selected items '
                            'Allows selection of more items via pop up'),
               used_for=('Products.Archetypes.Field.StringField',
                         'Products.Archetypes.Field.LinesField')
)
                     field,
                     form,
                     empty_marker=None,
                     emptyReturnsMarker=False):
        service_uids = form.get('uids', None)

        return service_uids, {}

    security.declarePublic('Analyses')

    def Analyses(self, field, instance, allow_edit=False):
        """Print analyses table
        """
        if instance.portal_type == 'SampleType':
            field_value = field.getAccessor(instance)()
        else:
            field_value = getattr(field, field.accessor)()

        view = ProjectAnalysesView(self,
                                   self.REQUEST,
                                   field_value=field_value,
                                   allow_edit=allow_edit)
        return view.contents_table(table_only=True)


registerWidget(
    ProjectAnalysesWidget,
    title='Project Analyses selector',
    description=('Project Analyses selector', ),
)
        name = field.getName()
        value = form.get(name, empty_marker)
        if value == '' or value == [''] and emptyReturnsMarker:
            return empty_marker
        return value, {}

    def is_keyword_field(self, field, source):
        """Returns whether or not a given field has a corresponding KeywordIndex
        in the specified catalog (source).
        """
        catalog = getToolByName(self,source)
        idxs = catalog.index_objects()
        filtered = [idx for idx in idxs if idx.id == field.accessor and
                    idx.meta_type == 'KeywordIndex' ]
        return filtered != []
    
    def makeVocab(self,list):
        """Takes in a list (of keywords) and returns a display list that
        is expected by the Vocabulary machinery.
        """
        dl = DisplayList()
        for i in list:
            dl.add(i,i)
        return Vocabulary(dl, None, None)

registerWidget(AJAXAddRemoveWidget,
                title = 'Add/Remove widget',
                description= ('Renders a HTML widget with two list boxes and add/remove buttons',),
                used_for = ('Products.Archetypes.Field.LinesField',)
                )
            for part_id in form['part_id'][0].keys():
                value.append({
                    'part_id':
                    part_id,
                    'preservation_uid':
                    form['preservation_uid'][0][part_id],
                    'container_uid':
                    form['container_uid'][0][part_id],
                })
        if value:
            return value, {}

    security.declarePublic('Partitions')

    def Partitions(self, field, allow_edit=False):
        """ Print partitions table
        """
        fieldvalue = getattr(field, field.accessor)()
        view = ARTemplatePartitionsView(self,
                                        self.REQUEST,
                                        fieldvalue=fieldvalue,
                                        allow_edit=allow_edit)
        return view.contents_table(table_only=True)


registerWidget(
    ARTemplatePartitionsWidget,
    title='AR Template Partition Layout',
    description=('AR Template Partition Layout'),
)
"""

from AccessControl import ClassSecurityInfo
from Products.Archetypes.public import StringWidget
from Products.Archetypes.Registry import registerWidget
from Products.Archetypes.Registry import registerPropertyType


class FormAutoFillWidget(StringWidget):
    # Vocabulary= function should return extra descriptions when
    # called with 'extended=True'
    security = ClassSecurityInfo()

    _properties = StringWidget._properties.copy()
    _properties.update(
        {"macro": "formautofill", "helper_url": None, "helper_text": "Open Subform", "icon": "autofill.png"}
    )


registerPropertyType("helper_url", "string", FormAutoFillWidget)
registerPropertyType("helper_text", "string", FormAutoFillWidget)
registerPropertyType("icon", "string", FormAutoFillWidget)

registerWidget(
    FormAutoFillWidget,
    title="Form Auto Fill",
    description="A string field which uses javascript to fill the rest of the form.",
    used_for=("Products.Archetypes.public.StringField", "Products.Archetypes.Field.LinesField"),
)
Beispiel #52
0
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
#$Id: COREBlogWidgets.py 133 2005-12-21 08:23:15Z ats $
#
##############################################################################

from Products.Archetypes.Widget import TypesWidget
from AccessControl import ClassSecurityInfo
from Products.Archetypes.Registry import registerWidget, registerPropertyType


class CategoryWidget(TypesWidget):
    _properties = TypesWidget._properties.copy()
    _properties.update({
        'macro': 'cbcategory_widget',
        'folderid': 'categories',  #folder id for category
        'helper_css': ('coreblogwidgets.css', ),
    })
    security = ClassSecurityInfo()


registerWidget(CategoryWidget,
               title='Category widgets',
               description="This is Category widget.",
               used_for=('Used for selecting category.', ))

registerPropertyType('folderid', 'string', CategoryWidget)
    def isRejectionEnabled(self, dd):
        """
        'd' is a dictionary with the stored data in the widget like:
        {u'selected': [u'a', u'b'], u'checkbox': True, u'other': 'dsadas', u'checkbox_other': True}
        Return whether the checkbox of the widget is enabled or not
        """
        return dd['checkbox'] if 'checkbox' in dd.keys() else False

    def getRejectionReasons(self,dd):
        """
        'd' is a dictionary with the stored data in the widget like:
        {u'selected': [u'a', u'b'], u'checkbox': True, u'other': 'dsadas', u'checkbox_other': True}
        Returns a string with the options both from selected and input items
        """
        keys = dd.keys()
        reasons = []
        if not('checkbox' in keys ) or not(dd['checkbox']):
            return 0
        if 'selected' in keys:
            reasons += dd['selected']
        if 'other' in keys and dd['checkbox_other']:
            reasons.append(dd['other'])
        if len(reasons) < 1:
            return "Yes, unknow"
        return ', '.join(reasons)

registerWidget(RejectionWidget,
               title = "Rejection Widget",
               description = ('Widget to choose rejection reasons and set the rejection workflow'),
               )
Beispiel #54
0
        :param key: id of the specs param to get (e.g. 'min')
        :param check_floatable: check if the value is floatable
        :param default: fallback value that will be returned by default
        :type default: str, None
        """
        if not form or not uid:
            return default
        values = form.get(key, None)
        if not values or len(values) == 0:
            return default
        value = values[0].get(uid, default)
        if not check_floatable:
            return value
        return api.is_floatable(value) and value or default

    security.declarePublic('AnalysisSpecificationResults')
    def AnalysisSpecificationResults(self, field, allow_edit = False):
        """ Prints a bika listing with categorized services.
            field contains the archetypes field with a list of services in it
        """
        fieldvalue = getattr(field, field.accessor)()
        view = AnalysisSpecificationView(self,
                                            self.REQUEST,
                                            fieldvalue = fieldvalue,
                                            allow_edit = allow_edit)
        return view.contents_table(table_only = True)

registerWidget(AnalysisSpecificationWidget,
               title = 'Analysis Specification Results',
               description = ('Analysis Specification Results'))
from Products.Archetypes.Registry import registerWidget


class CaptchaWidget(TypesWidget):
    _properties = TypesWidget._properties.copy()
    _properties.update({
        'modes': ('edit'),
        'visible': {'edit': 'visible', 'view': 'invisible'},
        'macro': 'captchawidget',
    })

InitializeClass(CaptchaWidget)

registerWidget(CaptchaWidget,
               title='CaptchaWidget',
               description=u'Renders a collective.recaptcha widget',
               used_for=('collective.atcaptchavalidation.Field.CaptchaField',)
               )


class CaptchaField(Field.ObjectField):
    """A field that stores strings"""
    _properties = Field.ObjectField._properties.copy()
    _properties.update({
        'type': 'captcha',
        'required': True,
        'widget': CaptchaWidget,
    })

    security = ClassSecurityInfo()
Beispiel #56
0
    security.declarePublic('get_template_rows')
    def get_template_rows(self, num_positions, current_field_value):
        try:
            num_pos = int(num_positions)
        except ValueError:
            num_pos = 10

        rows = []
        i = 1
        if current_field_value:
            for row in current_field_value:
                if num_pos > 0:
                    if i > num_pos:
                        break
                rows.append(row)
                i = i + 1
        for i in range(i, (num_pos + 1)):
            row = {
                'pos': i,
                'type': 'a',
                'sub': 1}
            rows.append(row)
        return rows


registerWidget(
    WorksheetTemplateLayoutWidget,
    title='WS Template Analyses Layout',
    description=('Worksheet analyses layout.'),
)
Beispiel #57
0
class AttachmentsManagerWidget(TypesWidget):
    """This widget adds support for uploading attachments into documents. To 
    support this, you must use it on a folderish type (derived from BaseFolder) 
    with 'FileAttachment' in the allowed_content_types. Create a BooleanField 
    and use this widget. This will display a form at the bottom of your edit 
    form (presuming it's the last widget, which it probably ought to be) where 
    you can upload images into your content type. The boolean field itself is
    used to select whether an attachment download box should be presented. This
    is similar to the "related items" box in Plone.
    
    Content editors may also reference the images directly in their body
    text.
    
    Caveats: In the edit macro, the upload button may steal the default 
    enter-key-press in base_edit.
    """

    # Use the base class properties, and add two of our own
    _properties = TypesWidget._properties.copy()
    _properties.update({'macro'     : 'widget_attachmentsmanager',
                        'expanded'  : False,
                        },)

# Register the widget with Archetypes
registerWidget(AttachmentsManagerWidget,
               title = 'Attachments manager widget',
               description= ('Renders controls for uploading attachments to documents',),
               used_for = ('Products.Archetypes.Field.BooleanField',)
               )
Beispiel #58
0
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright 2018-2019 by it's authors.
# Some rights reserved, see README and LICENSE.

from AccessControl import ClassSecurityInfo
from Products.ATExtensions.widget import RecordWidget
from Products.Archetypes.Registry import registerWidget
import datetime


class DurationWidget(RecordWidget):
    security = ClassSecurityInfo()
    _properties = RecordWidget._properties.copy()
    _properties.update({
        'macro': "bika_widgets/durationwidget",
    })


registerWidget(
    DurationWidget,
    title='DurationWidget',
    description=(''),
)
                    keyval = form[key][0].get(uid, '') if key in form else ''
                    keyval = keyval if isnumber(keyval) else ''
                    values[i][j][key] = keyval
        return values

    security.declarePublic('AnalysisSpecificationResults')
    def AnalysisSpecificationResults(self, field, allow_edit=False):
        fieldvalue = getattr(field, field.accessor)()
        view = AnalysisSpecificationView(self,
                                            self.REQUEST,
                                            fieldvalue=fieldvalue,
                                            allow_edit=allow_edit)
        return view.contents_table(table_only=True)

registerWidget(AnalysisSpecificationWidget,
               title='Analysis Specification Results',
               description=('Analysis Specification Results'))


class AnalysisSpecificationPanicValidator:
    implements(IValidator)
    name = "analysisspecs_panic_validator"

    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        ts = getToolByName(instance, 'translation_service').translate

        if instance.REQUEST.get('validated', '') == self.name:
            return True
        else:
            instance.REQUEST['validated'] = self.name
Beispiel #60
0
                newData = newData[:-1]

        return (newData, value[1])

    def savePostbackData(self, REQUEST, context, field, formData):
        """ Gets the value of a cell

        We cannot solely rely DataGridField.get which
        does ObjectField.get(), since form postback data
        can contain custom fields which are not directly mapped
        like Zope expects (e.g. fields with more than one <input>)

        XXX Need refactoring/clean up
        """

        # Column code hook to form data and manipulate
        # it propeply where TypesWidget.process_form doesn't
        # have required functionality
        for columnId in getattr(self, 'columns', {}).keys():
            columnDefinition = self.getColumnDefinition(field, columnId)
            formData = columnDefinition.processCellData(
                REQUEST, formData, context, field, columnId)


__all__ = ('DataGridWidget')

registerWidget(DataGridWidget,
               title='Data Grid',
               description=('A spreadsheet like table'),
               used_for=('Products.DataGridField.DataGridField', ))