'''This file is a MixIn to make it easier to use FormKit with Webware. You can still use
FormKit (with or without Webware) and NOT use this file, but you will have to do certain
operations more manually.'''
from WebKit.Cookie import Cookie
import time
class FormKitMixIn:
'''IMPORTANT: This MixIn must be inherited first, because it overwrites methods
of WebKit. Those methods are preAction and postAction, and are essentially non-
destructive (no methods that get called stock do not get called here).'''
def addForm(self,formInstance):
'''adds the passed-in form instance to the list of forms self._forms,
AND sets the numeric id for that appended form instance.'''
if not hasattr(self,'_forms'):
self._forms = [ ]
self._forms.append(formInstance)
num = len(self._forms) - 1
self._forms[-1]._setFormID(num)
def resetForms(self):
'''resets all forms in this servlet... needs to be called either from a servlet's .sleep()
or in .awake() before any seed() calls.'''
for form in self._forms:
if hasattr(form, '_error'):
form._error = None
form.reset()
def preAction(self,actionName):
'''Overwrites WebKit method so that a form can be processed by FormKit.'''
fields = self.request().fields()
formID = fields.get('__formID__')
if formID:
formID = int(formID)
form = self._forms[formID]
form.process( fields )
if form.isSuccessful():
self.storePersistent()
def postAction(self, actionName):
'''Overwrites WebKit method so that a form can be re-painted when there are input errors.'''
self.writeHTML()
def storePersistent(self, days=30):
'''stores any fields marked as persistent into cookies.
Optionally pass days for the time.time
REQUIRES self.persistFields to work, but will not crash if it's not there.'''
if hasattr( self, 'persistDays') and self.persistDays is not None:
days = self.persistDays
if hasattr( self, 'persistFields' ):
for field in self.persistFields():
self.setCookie( field, self.form.field(field).value(), days )
def clearPersistent(self):
'''clears any fields that are self.persistFields()'''
if hasattr( self, 'persistFields' ):
for field in self.persistFields():
self.clearCookie( field )
def setCookie(self, key, value, days):
'''just a helper method to set cookies'''
cookie = Cookie(key, value)
t = time.gmtime( time.time() + days*24*60*60 )
t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
cookie.setExpires(t)
cookie.setPath('/')
self.response().addCookie(cookie)
def clearCookie(self, key):
'''just a helper method to clear cookies'''
cookie = Cookie(key, '')
t = time.gmtime(time.time() - 3600 )
t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
cookie.setExpires(t)
cookie.setMaxAge(0)
cookie.setPath('/')
self.response().addCookie(cookie)