Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plone/zope.schema- How do I set the year range on a date widget between two dates?

Tags:

zope

plone

In my form (plone.directives.form.SchemaForm), I am using a schema containing a date field (zope.schema.Date) and the datefield is set as a datepicker widget automatically.

Edit: I'm using Plone 4.3.9

The widget's default year range is automatically set between -10 years and +10 years relative to a date.

I tried making a widget factory for the date field and setting the year range

from z3c.form.widget import FieldWidget
from zope.component import adapter
from zope.interface import implementer
from plone.directives import form
from datetime import date
from plone.formwidget.datetime.z3cform import DateWidget
from plone.supermodel import model
from z3c.form.interfaces import IFieldWidget

@implementer(IFieldWidget)
def DateFieldWidget(field, request):
    widget = FieldWidget(field, DateWidget(request))
    start = -(date.today().year - 1984)
    end = 10
    widget.years_range = (start, end)
    return widget

class IMyObject(model.Schema):
    ...
    form.widget('Prev_Date',DateFieldWidget)
    Prev_Date = schema.Date(
        title=u"Previous Date",
        description=u"A previous date",
        required=False,
    )

This only works in an add form, where it sets between a year, in the example I provided 1984 and 10 years from today's year. In the edit form, the first and last years available for selection are off.

I did try checking to see if maybe I could check to see if the value is set, but in the edit form, I'm getting an empty value, even if its been set.

@implementer(IFieldWidget)
def DateFieldWidget(field, request)
    widget = FieldWidget(field, DateWidget(request))
    #widget.value is a tuple
    defaultEndOfRange = 10
    try:
        start = -(int(widget.value[0]) - 1984)
        end = defaultEndOfRange - (int(widget.value[0]) - date.today().year)
    except:
        start = -(date.today().year - 1984)
        end = defaultEndOfRange
    widget.years_range = (start,end)
    return widget

I could do this in an updateWidgets function instead of using a widget factory, but I have two dexterity content types that I have not made custom add and edit forms for and I want to use the same year range on a couple of different fields.

Since this isn't working, what would be a better approach? Or should I stick with creating add and edit forms?

like image 860
Patrick Downey Avatar asked Nov 20 '25 19:11

Patrick Downey


1 Answers

In my Interface of Form i have this definition for a Date Field:

from collective.z3cform.datetimewidget import DateWidget    
....
....
....    
form.widget('birthday', DateWidget)
birthday = schema.Date(
  title=_(u'Birthday'),
  description=_(u'your birthday'),
  required=True,
  min = date(1950,1,1),
  max = date(2015,1,1))

But it's a Plone 4 Solution.

like image 99
1letter Avatar answered Nov 22 '25 17:11

1letter