Home Company Services Portfolio Contact us nav spacer

Using form widgets anywhere

by hedley posted on Oct 03, 2009 07:35 PM last modified Oct 04, 2009 02:23 PM

z3c.form and a few other products provide nice widgets for use with schema driven forms. This post shows how to use such a standalone contextless widget in a template.

Sometimes I don't want to setup a schema to create a form. I frequently collide with the forms framework when all I really want to do is use that snazzy autocomplete widget in my Plone registration form. Rewriting the registration form is obviously not an option, so let's reuse that widget.

For our example I'm using the DateWidget from collective.z3cform.datetimewidget since that highlights a few other isues. Typically we'll have a browser view with this method

import datetime
from zope.interface import alsoProvides
from collective.z3cform.datetimewidget.widget import DateWidget
from z3c.form.interfaces import IFormLayer

def when_widget(self):
     alsoProvides(self.request, IFormLayer) 
     if not hasattr(self.request, 'locale'):
         self.request.locale = getLocale(self.request)
     widget = DateWidget(self.request)
     widget.name = 'when'
     widget.ignoreContext = True
     widget.update()
     return widget.render()

Note the IFormLayer and request.locale gotchas.

Update: Martin Aspeli sent me a better method.

import datetime
from collective.z3cform.datetimewidget.widget import DateWidget
from plone.z3cform import z2

def when_widget(self):
     z2.switch_on(self)
     widget = DateWidget(self.request)
     widget.name = 'when'
     widget.ignoreContext = True
     widget.update()
     return widget.render()

In a template we do

<span tal:replace="structure view/when_widget" />