Example #1
0
 def get_collection_schema_from_interface_schema(self, schema):
     collection = {}
     for name in schema:
         if IDate.providedBy(schema[name]) or \
                                             IDatetime.providedBy(schema[name]):
             collection['field.'+name] = 'time'
         elif IDecimal.providedBy(schema[name]) or \
                             IFloat.providedBy(schema[name]) or \
                                            IInt.providedBy(schema[name]):
             collection['field.'+name] = 'number'
         elif IBool.providedBy(schema[name]):
             collection['field.'+name] = 'bool'
         elif ICollection.providedBy(schema[name]):
             if not ICollection.providedBy(schema[name].value_type) and not \
                         IDict.providedBy(schema[name].value_type):
                 collection['field.'+name] = 'array'
         elif IDict.providedBy(schema[name]):
             if IText.providedBy(schema[name].key_type) and \
                         IText.providedBy(schema[name].value_type):
                 collection['field.'+name] = 'array'
         # this is a pretty weak check for a IP address field.  We might want
         # to update this to look for a field validator based on the ipaddress package
         # or mark this field with a special interface indicating it is an 
         # IP address
         elif IDottedName.providedBy(schema[name]) and \
                         (schema[name].min_dots == schema[name].max_dots == 3):
             collection['field.'+name] = 'cidr'
         elif IText.providedBy(schema[name]) or \
                                     INativeString.providedBy(schema[name]):
             collection['field.'+name] = 'string'
     return collection
    def renderJS(self):
        url = '/'.join(self.request.physicalPathFromURL(self.request.getURL()))
        widgetURL = '%s/++widget++%s/@@masterselect-jsonvalue' % (
            url, self.__name__)

        for slave in self.getSlaves():
            slave['slaveID'] = self.get_slave_id(slave)
            slave['url'] = widgetURL
            slave['masterID'] = '#' + slave.get('masterID', self.id)
            slave['siblings'] = slave.get('siblings', False)
            slave['empty_length'] = int(slave.get('empty_length', 0))
            slave.setdefault('control_param', 'master_value')

            if 'hide_values' in slave:
                values = slave['hide_values']
                if not isinstance(values, (tuple, list)):
                    values = [values]
                if IBool.providedBy(self.field):
                    values = [boolean_value(v) for v in values]
                slave['values'] = values

            js_template = BINDERS.get(slave.get('action')) or BINDERS['toggle']

            # Remove some things from slave we don't need
            slave.pop('vocab_method', None)
            slave.pop('hide_values', None)
            slave.pop('control_param', None)

            settings = {
                'masterID': slave['masterID'],
                'json': json.dumps(slave)
            }
            yield js_template % settings
Example #3
0
 def test_externalKeywordTest(self):
     fields = FormFields(ISEOConfigletSchema)
     ffield = fields.get("external_keywords_test")
     self.assertTrue(ffield is not None, 'Not found "external_keywords_test" '\
         'field in ISEOConfigletSchema interface')
     self.assertTrue(IBool.providedBy(ffield.field),
         '"external_keywords_test" is not boolean type field')
     self.assertTrue(ffield.field.default == False,
         '"external_keywords_test" field default value is not set to False')
Example #4
0
 def test_externalKeywordTest(self):
     fields = FormFields(ISEOConfigletSchema)
     ffield = fields.get("external_keywords_test")
     self.assertTrue(
         ffield is not None, 'Not found "external_keywords_test" field in '
         'ISEOConfigletSchema interface')
     self.assertTrue(IBool.providedBy(ffield.field),
                     '"external_keywords_test" is not boolean type field')
     self.assertTrue(
         ffield.field.default is False,
         '"external_keywords_test" field default value '
         'is not set to False')
Example #5
0
    def clean_field(self, organization, fieldname, field):
        if ITextLine.providedBy(field):
            setattr(organization, fieldname, "")
        elif ITuple.providedBy(field):
            setattr(organization, fieldname, [])
        elif IBool.providedBy(field):
            setattr(organization, fieldname, False)
        elif IRichText.providedBy(field):
            richvalue = RichTextValue("", 'text/html', 'text/html')
            setattr(organization, fieldname, richvalue)
        else:
            logger("[Error] Field '%s' type is not recognised. " %(fieldname), "Field cannot be cleaned before sync.")

        return organization
    def renderJS(self):
        url = '/'.join(self.request.physicalPathFromURL(self.request.getURL()))
        widgetURL = url + '/++widget++%s/@@masterselect-jsonvalue' % self.__name__

        for slave in self.getSlaves():
            if not 'slaveID' in slave:
                # Try to get it from widget
                widget = self.form.widgets.get(slave['name'])
                if widget is not None and getattr(widget, 'id', None) is not None:
                    slave['slaveID'] = '#' + widget.id
                else:
                    # Try our best to create one; won't work for checkboxes, so
                    # better to provide a slaveID in the schema in that case or
                    # sometimes to increase the scope beyond the field
                    prefix = '-'.join(self.id.split('-')[:-1])
                    slave['slaveID'] = '#%s-%s' % (prefix, slave['name'])

            slave['url'] = widgetURL
            slave['masterID'] = slave.get(
                'masterSelector',
                '#' + slave.get('masterID', self.id)
                )
            slave['siblings'] = slave.get('siblings', False)
            slave['empty_length'] = int(slave.get('empty_length', 0))
            slave.setdefault('control_param', 'master_value')

            if 'hide_values' in slave:
                values = slave['hide_values']
                if not isinstance(values, (tuple, list)):
                    values = [values]
                if IBool.providedBy(self.field):
                    values = [boolean_value(v) for v in values]
                #else:
                #    values = [str(v) for v in values]
                slave['values'] = values

            js_template = BINDERS.get(slave.get('action')) or BINDERS['toggle']

            # Remove some things from slave we don't need
            slave.pop('vocab_method', None)
            slave.pop('hide_values', None)
            slave.pop('control_param', None)

            settings = {'masterID': slave['masterID'],
                        'json': json.dumps(slave)
                       }
            yield js_template % settings
Example #7
0
    def renderJS(self):
        url = '/'.join(self.request.physicalPathFromURL(self.request.getURL()))
        widgetURL = url + '/++widget++%s/@@masterselect-jsonvalue' % self.__name__

        for slave in self.getSlaves():
            if not 'slaveID' in slave:
                # Try to get it from widget
                widget = self.form.widgets.get(slave['name'])
                if widget is not None and getattr(widget, 'id',
                                                  None) is not None:
                    slave['slaveID'] = '#' + widget.id
                else:
                    # Try our best to create one; won't work for checkboxes, so
                    # better to provide a slaveID in the schema in that case or
                    # sometimes to increase the scope beyond the field
                    prefix = '-'.join(self.id.split('-')[:-1])
                    slave['slaveID'] = '#%s-%s' % (prefix, slave['name'])

            slave['url'] = widgetURL
            slave['masterID'] = slave.get('masterSelector',
                                          '#' + slave.get('masterID', self.id))
            slave['siblings'] = slave.get('siblings', False)
            slave['empty_length'] = int(slave.get('empty_length', 0))
            slave.setdefault('control_param', 'master_value')

            if 'hide_values' in slave:
                values = slave['hide_values']
                if not isinstance(values, (tuple, list)):
                    values = [values]
                if IBool.providedBy(self.field):
                    values = [boolean_value(v) for v in values]
                #else:
                #    values = [str(v) for v in values]
                slave['values'] = values

            js_template = BINDERS.get(slave.get('action')) or BINDERS['toggle']

            # Remove some things from slave we don't need
            slave.pop('vocab_method', None)
            slave.pop('hide_values', None)
            slave.pop('control_param', None)

            settings = {
                'masterID': slave['masterID'],
                'json': json.dumps(slave)
            }
            yield js_template % settings
Example #8
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
Example #9
0
 def _populate_record(self, entry, data):
     changelog = []
     schema = entry.schema
     for name, _field in getFieldsInOrder(schema):
         if IDate.providedBy(_field):
             v = self._normalize_date_value(_field, data)
             if v is not None:
                 _field.validate(v)    # no enforcement of required here.
             setattr(entry, name, v)  # new value is possibly empty
             continue
         if name in data:
             value = data.get(name, None)
             if value in (u'true', u'false') and IBool.providedBy(_field):
                 value = True if value == 'true' else False  # radio widget
             if value == NOVALUE:
                 value = None
             cast_type = field_type(_field)
             if cast_type:
                 if cast_type is int and isinstance(value, basestring):
                     value = value.replace(',', '')
                 if cast_type is unicode and isinstance(value, str):
                     value = value.decode('utf-8')
                 elif (cast_type is datetime and
                       isinstance(value, basestring)):
                     fn = converter.DatetimeDataConverter(_field,
                                                          TEXT_WIDGET)
                     value = fn.toFieldValue(unicode(value))
                 else:
                     try:
                         value = cast_type(value)
                     except (ValueError, TypeError):
                         pass
             if value not in (None, ''):
                 _field.validate(value)
                 existing_value = getattr(entry, name, None)
                 if value != existing_value:
                     changelog.append(name)
                 setattr(entry, name, value)
             else:
                 # empty -> possible unset of previously set value in form?
                 setattr(entry, name, None)
     entry._p_changed = True  # in case of collection fields
     if changelog:
         changelog = [Attributes(schema, name) for name in changelog]
         notify(ObjectModifiedEvent(entry, *changelog))
Example #10
0
 def _populate_record(self, entry, data):
     changelog = []
     schema = entry.schema
     for name, _field in getFieldsInOrder(schema):
         if IDate.providedBy(_field):
             v = self._normalize_date_value(_field, data)
             if v is not None:
                 _field.validate(v)  # no enforcement of required here.
             setattr(entry, name, v)  # new value is possibly empty
             continue
         if name in data:
             value = data.get(name, None)
             if value in (u'true', u'false') and IBool.providedBy(_field):
                 value = True if value == 'true' else False  # radio widget
             if value == NOVALUE:
                 value = None
             cast_type = field_type(_field)
             if cast_type:
                 if cast_type is int and isinstance(value, basestring):
                     value = value.replace(',', '')
                 if cast_type is unicode and isinstance(value, str):
                     value = value.decode('utf-8')
                 elif (cast_type is datetime
                       and isinstance(value, basestring)):
                     fn = converter.DatetimeDataConverter(
                         _field, TEXT_WIDGET)
                     value = fn.toFieldValue(unicode(value))
                 else:
                     try:
                         value = cast_type(value)
                     except (ValueError, TypeError):
                         pass
             if value not in (None, ''):
                 _field.validate(value)
                 existing_value = getattr(entry, name, None)
                 if value != existing_value:
                     changelog.append(name)
                 setattr(entry, name, value)
             else:
                 # empty -> possible unset of previously set value in form?
                 setattr(entry, name, None)
     entry._p_changed = True  # in case of collection fields
     if changelog:
         changelog = [Attributes(schema, name) for name in changelog]
         notify(ObjectModifiedEvent(entry, *changelog))
Example #11
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
Example #12
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
    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 = "No value"
        elif ITextLine.providedBy(field):
            type_field = " "
        elif IList.providedBy(field):
            type_field = []
        elif IText.providedBy(field):
            type_field = " "
        elif IRichText.providedBy(field):
            type_field = " "
        elif IBool.providedBy(field):
            type_field = False
        else:
            type_field = " "

        return type_field