[SOLVED] Format Integer Widget

I have a simple Field "year" with type zope.schema.Int. I would disable the formatter for values larger than 1000, but how? When i call the form to edit the values, the year field display 1.990, but i need 1990. Has anyone practical knowledge?

I had the same issue some time ago with a year field. I ended up creating my own Year field by subclassing zope.schema.Int and overwriting the formatter in my own class.

-aj

Only for other guys, that search a solution

For all Fields of schema.Int i registered my own Dataconverter (inspired by Stackoverflow Post)

# converter.py

# -*- coding: utf-8 -*-
from zope.component import provideAdapter
from zope.component import adapts
from zope.schema.interfaces import IInt
from z3c.form.interfaces import ITextWidget
from z3c.form.converter import IntegerDataConverter

class NoFormatIntegerDataConverter(IntegerDataConverter):

    adapts(IInt, ITextWidget)    

    def toWidgetValue(self, value):
        if value is self.field.missing_value:
            return u''
        return unicode(value)

provideAdapter(NoFormatIntegerDataConverter)
<!-- configure.zcml -->
....
<!-- Data Converters -->
    <adapter
        factory=".converter.NoFormatIntegerDataConverter" />
....

If needed only for a particular Int-Widget, then write your own Widget like:

# widget.py
# -*- coding: utf-8 -*-
from zope.component import adapter
from zope.interface import implementer
from zope.schema.interfaces import IField

from z3c.form.interfaces import IFormLayer
from z3c.form.interfaces import IFieldWidget
from z3c.form.interfaces import ITextWidget
from z3c.form.browser.text import TextWidget

class IIntNoFormatWidget(ITextWidget):
    pass

@implementer(IIntNoFormatWidget, IMyFormFieldWidget)        
class IntNoFormatWidget(TextWidget):

    id = u'int-no-format-widget'
    
    def update(self):        
        super(IntNoFormatWidget, self).update()
        
    def render(self):
        return super(IntNoFormatWidget, self).render()
        

@adapter(IField, IFormLayer)
@implementer(IFieldWidget)
def IntNoFormatFieldWidget(field, request): 
    return widget.FieldWidget(field, IntNoFormatWidget(request))

and change the Code in the converter.py to

# converter.py

# -*- coding: utf-8 -*-
from zope.component import provideAdapter
from zope.component import adapts
from zope.schema.interfaces import IInt
from z3c.form.interfaces import ITextWidget
from z3c.form.converter import IntegerDataConverter

class NoFormatIntegerDataConverter(IntegerDataConverter):

    # adapts the Widget Definition above
    adapts(IInt, IIntNoFormatWidget)    

    def toWidgetValue(self, value):
        if value is self.field.missing_value:
            return u''
        return unicode(value)

provideAdapter(NoFormatIntegerDataConverter)
2 Likes