Yes, we do almost exactly this same thing using FFK. A single set of mutable
form definitions (which are really just placeholders for the wildly different
forms that might be created during awake) are used to modify db data. Well,
like you said.
It's been a long time since I've looked at the core of this code, I know we had
to make a few changes to how mutable forms work. I'm attaching our copy of
FFK/Form.py (which is from 0.3 I believe), I don't have time right now to diff
and explain, but maybe I will later if there are questions? Largest thing I
remember is throwing out the dynamic serial formID, and fixing some missing
stuff with removeField/replaceField.
Anyways. Last I talked to Ian about this, Mutable forms really hadn't been
tested very much at all. We now use them all the time, particularily in this
app, but I never communicated our changes (nothing really structural) to Ian.
I've been meaning to look at upgrading to FFK 0.4, maybe Ian can speak to
how/if mutable forms have changed in this rewrite?
If you've got any questions, let me know.
Luke
Quoting Aaron Held <[EMAIL PROTECTED]>:
> Has anyone tried to create fully dynamic form definitions using FFK?
>
> I am thinking of an app that would dynamically generate an HTML
> interface to a given table.
>
> Assuming that the table metadata and business rules do not change it
> should be relatively easy to create a form using the mutable
> formdefinition and validators.
>
> So if you want to track birthdays the SQL table could have a date, name
> and age field.
> The FFK would pick out a date and two text fields, One of the text would
> have a validator to specify an integer >= 0.
>
> Currently mutable form uses a module variable to store a copy of the
> form def once it is created. I would rather create it on the fly each
> time.
>
> (I know that there are all sorts of consistancy issues and the form def
> cannot change in the middle of a session)
>
> Thanks,
> -Aaron
>
>
>
> -------------------------------------------------------
> This sf.net email is sponsored by:ThinkGeek
> Welcome to geek heaven.
> http://thinkgeek.com/sf
> _______________________________________________
> Webware-discuss mailing list
> [EMAIL PROTECTED]
> https://lists.sourceforge.net/lists/listinfo/webware-discuss
>
>
## FunFormKit, a Webware Form processor
## Copyright (C) 2001, Ian Bicking <[EMAIL PROTECTED]>
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this library; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
## NOTE: In the context of the Python environment, I interpret "dynamic
## linking" as importing -- thus the LGPL applies to the contents of
## the modules, but make no requirements on code importing these
## modules.
"""
FunFormKit, a Webware Form processor
Copyright (C) 2001, Ian Bicking <[EMAIL PROTECTED]>
This defines a Form mixin with a number of classes used to define the
fields in forms. A number of classes are declared in this module, but
it is fairly safe to import * from this module.
See the documentation for the Form class for more information.
"""
from WebKit.Common import *
from WebUtils.Funcs import htmlEncode
import threading
from Signature import Signature
True, False = (0==0), (1==0)
class FormError(Exception):
"""Some runtime form errors raise this exception."""
pass
class FormServlet:
"""
This class should be mixed in with your servlet. You must
call the __init__ method.
The only interesting method you'll call is
.renderableForm(formDefinition, defaults={}, rawDefaults={},
optionSet={})
The formDefinition is one of the FormDefinitions you passed to
__init__, the name of that form, or you can leave it out if the
servlet only implements one FormDefinition.
defaults is a dictionary of the values the fields should display
when first presented. It doesn't apply to forms that are
represented after errors.
rawDefaults are a list of, well, raw values. If you take
.response().fields() and save it, you can recreate the form
later by passing that as rawDefaults. You might use this when
you accept partial forms -- but the infrastructure isn't really
there for this yet.
optionSet is a dictionary of fieldName: optionDict. The optionDict
depends on the field, but all fields support "hide": 1, which will
suppress the field and make it hidden. DynamicSelectField uses
options.
Look at RenderableForm for a description of the object you get
back.
@@ 2001-22-07 ib: I've noticed that this makes very
little use of its mixin status. Should this be an entirely
seperate object? I'm not sure... saving state in self is
nice.
"""
def __init__(self, overrideMethod,
formDefinitions = [],
defaultFormDefinition = None,
defaultFormRenderMethod = None):
setattr(self, overrideMethod, self._processForm)
if type(defaultFormRenderMethod) is type(""):
# otherwise we're supposing its the actual method itself
defaultFormRenderMethod = getattr(self, defaultFormRenderMethod)
self._defaultFormRenderMethod = defaultFormRenderMethod
if defaultFormDefinition is None:
if defaultFormRenderMethod:
self._defaultFormRenderMethod = defaultFormRenderMethod
self._defaultFormDefinition = None
else:
assert len(formDefinitions) == 1, "You must give a default form
definition when a servlet handles more than one form."
self._defaultFormDefinition = formDefinitions[0]
else:
self._defaultFormDefinition = defaultFormDefinition
self._formDefinitions = {}
for formDefinition in formDefinitions:
self._formDefinitions[formDefinition.formID()] = formDefinition
def renderableForm(self, formDefinition=None, defaults={},
rawDefaults=None, optionSet = {}):
if formDefinition is None:
assert len(self._formDefinitions) == 1
formDefinition = self._formDefinitions.values()[0]
if type(formDefinition) is type(""):
formDefinition = self._formDefinitions[formDefinition]
#if self._erroneousRequest:
# if not self._erroneousFormName == formDefinition.name():
# raise FormError, \
# "Upon error you must render the form that caused the error --
form %s had an error and you tried to render %s" % \
# (self._erroneousFormName, formDefinition.name())
if self._erroneousFormName == formDefinition.name():
requestFields = self._erroneousRequest.fields()
errors = self._errors
else:
requestFields = rawDefaults
errors = {}
return RenderableForm(formDefinition, requestFields=requestFields,
defaults=defaults, optionSet=optionSet,
errors=errors)
def _processForm(self, transaction = None):
self._erroneousRequest = None
self._errors = None
self._erroneousFormName = None
if transaction:
req = transaction.request()
else:
req = self.request()
currentForm = None
if req.hasField('_formID_'):
formID = req.field('_formID_')
if formID[:7] == "dynamic":
currentForm = MutableFormDefinitionStore[int(formID[-6:])]
else:
currentForm = self._formDefinitions[req.field('_formID_')]
elif len(self._formDefinitions) == 1:
for fieldName in self._formDefinitions.values()[0].submitFields().keys():
if req.hasField(fieldName):
currentForm = self._formDefinitions.values()[0]
break
if not currentForm:
if not self._defaultFormDefinition:
return getattr(self,
self._defaultFormRenderMethod)()
else:
return getattr(self,
self._defaultFormDefinition.renderMethodName())()
valid = False
for fieldName, field in currentForm.fields().items():
if field.isSubmit() and field.suppressValidation() and \
req.field(field.name(), None):
valid = True
data = req.fields()
actionMethod = field.methodToInvoke()
invokeAsFunction = field.invokeAsFunction()
noneAsDefault = field.noneAsDefault()
break
if not valid:
valid, data, actionMethod, invokeAsFunction, noneAsDefault = \
currentForm.validateConvert(req)
if valid:
method = getattr(self, actionMethod)
if not invokeAsFunction:
method(data)
else:
invokeFunctionWithDict(method, data, noneAsDefault=noneAsDefault)
else:
self._erroneousRequest = req
self._erroneousFormName = currentForm.name()
self._errors = data
getattr(self, currentForm.renderMethodName())()
class RenderableForm:
"""
This is kind of a wrapper around the FormDefinition. FormDefinition
is meant to be static across calls, not holding any real state. So
RenderableForm is an object that is created and collected all the
time. It will be the primary interface you use to generate the form
-- which you can do with .htFormTable() (easy and quick), Cheetah
(flexible and fairly easy too), or just with self.write().
To use Cheetah, you should be able to put the RenderableForm that
you get from FormServlet in the namespace, and use $form.username,
$form.username.error, $form.error, etc.
For self.write(), use things like rf["username"],
rf["username"].error(), rf.error(), etc.
Be sure to start and end the form properly! Use $form.start or
self.write(rf.start()). htFormTable() deals with this itself,
of course.
"""
def __init__(self, formDefinition, requestFields = None,
defaults = {}, errors = {}, optionSet = {}):
"""The arguments are passed pretty much directly through from
FormServlet.renderableForm()."""
self._formDefinition = formDefinition
self._requestFields = requestFields
self._defaults = defaults
self._errors = errors
self._optionSet = optionSet
def __getattr__(self, item):
"""You *never* get the actual fields back from RenderableForm,
but rather you get the fields wrapped in a RenderableField
class. There are several accessors that follow this."""
## Some Python 2.1 thing... I don't really understand why
## these attributes are called. Should fix/figure out at
## some point.
if item in ['__del__', '__eq__']:
raise AttributeError
else:
return RenderableField(self, item)
def __getitem__(self, item):
return self.__getattr__(item)
def error(self):
if self._errors.get('form'):
return self._formDefinition._errorFormatter(self._errors['form'])
else:
return ''
def errorText(self):
return self._errors.get('form', '')
def fieldList(self, fieldNames):
return map(lambda x, s=self: RenderableField(s, x),
fieldNames)
def fields(self):
return self.fieldList(self._formDefinition.fieldNames())
def visibleFields(self):
return
self.fieldList(self._formDefinition.visibleFieldNames(optionSet=self._optionSet))
def hiddenFields(self):
return
self.fieldList(self._formDefinition.hiddenFieldNames(optionSet=self._optionSet))
def submitFields(self):
return
self.fieldList(self._formDefinition.submitFieldNames(optionSet=self._optionSet))
def htStartForm(self, includeHiddenFields = False):
return self._formDefinition.htStartForm(
requestFields=self._requestFields, defaults=self._defaults,
optionSet=self._optionSet,
includeHiddenFields=includeHiddenFields)
def htEndForm(self):
return self._formDefinition.htEndForm(
None, self._optionSet)
def htHiddenFields(self):
result = []
for fieldName in self._formDefinition.fieldNames():
field = self._formDefinition.field(fieldName)
if field.isHidden(options=self._optionSet.get(fieldName, {})):
result.append(str(self[fieldName]))
return string.join(result, "\n")
def start(self):
return self.htStartForm()
def end(self):
return self.htEndForm()
def hidden(self):
return self.htHiddenFields()
def htFormTable(self, bgcolor=None):
html = StringIO()
html.write(self.htStartForm(True))
html.write(self.error())
if bgcolor:
html.write('<table bgcolor="%s">\n' % bgcolor)
else:
html.write('<table>\n')
for field in self.fields():
if field.isSubmit():
html.write('<tr><td colspan=2 align=center>%s%s</td></tr>\n'
% (field.error(), field.html()))
elif not field.isHidden():
html.write('<tr><td align="right" valign="top">%s</td>\n' %
htmlEncode(field.description()))
html.write('<td align="left">%s%s</td></tr>\n' %
(field.error(), field.html()))
html.write('</table>')
return html.getvalue()
class RenderableField:
"""
RenderableField is a wrapper around a field, tightly coupled with
the RenderableForm that created it.
RenderableField is a close friend (really just a wrapper) of
RenderableForm. So it uses private variables at will.
"""
def __init__(self, renderableForm, name):
self._name = name
self._rf = renderableForm
self._field = renderableForm._formDefinition._fields[name]
self._fieldName = self._field.name()
def html(self):
return self._field.html(requestFields =
self._rf._requestFields,
defaults = self._rf._defaults,
optionSet = self._rf._optionSet)
def __str__(self):
return self.html()
def error(self):
if self._rf._errors.get(self._name):
return
self._rf._formDefinition._errorFormatter(self._rf._errors[self._name])
else:
return ''
def errorText(self):
return self._rf._errors.get(self._name, '')
## @@ 2001-07-20 ib: Maybe I should just pass everything else onto
## the actual field, instead of just passing these methods through.
def description(self):
return self._field.description()
def name(self):
return self._field.name()
def isSubmit(self):
return self._field.isSubmit()
def isHidden(self):
return self._field.isHidden(options=self._rf._optionSet.get(self._fieldName,
{}))
def option(self, name, default=None):
return self._field.option(name,
options=self._rf._optionSet.get(self._fieldName, {}), default=default)
def defaultFormatError(value):
"""
It prints the error message in red with white text.
"""
if type(value) is type([]):
value = string.join(value, " <br>\n")
return '<span style="background: #aa0000; color: #ffffff">%s</span><br>' \
% value
class FormDefinition:
"""
A FormDefinition declares what fields the form will have, among
other details about the form. You shouldn't be creating these
definitions dynamically. (For experimental support for doing that,
look at MutableFormDefinition)
@@ 2001-07-21 ib: get rid of the handlerServletURL or something --
as it is, it can't deal with changing adapters, or generally being
reflective about the location Webware is installed.
"""
def __init__(self, handlerServletURL, renderMethod,
fields, formValidators=[],
method="POST", enctype=None, name="form",
errorFormatter=defaultFormatError):
"""
* handlerServletURL is the URL of servlet that handles the
results of the form.
* renderMethod is the method in that servlet that gets invoked
to display the form (when an error occurs).
* fields is a list of fields (see the Fields module for more
about them).
* formValidators is a list of validators. See
Validator.FormValidators for more about their interface.
name should be unique within the servlet. enctype you can
safely ignore -- the <form enctype> will automatically be
set if you use a FileField. method is obvious.
"""
self._handlerServletURL = handlerServletURL
self._renderMethod = renderMethod
self._name = name
self._method = method
self._formValidators = formValidators
self._fields = {}
self._fieldOrder = []
self._submitFields = {}
self._errorFormatter = errorFormatter
for field in fields:
name = field.name()
self._fields[name] = field
self._fieldOrder.append(name)
if not enctype and field.preferedEnctype():
enctype = field.preferedEnctype()
if field.isSubmit():
self._submitFields[name] = field
self._enctype = enctype
def formID(self):
return self._name
def submitFields(self):
return self._submitFields
def fieldNames(self):
return self._fieldOrder
def visibleFieldNames(self, optionSet={}):
return filter(lambda name, self=self, op=optionSet: not
self._fields[name].isHidden(options=op.get(name, {})),
self._fieldOrder)
def hiddenFieldNames(self, optionSet={}):
return filter(lambda name, self=self, op=optionSet:
self._fields[name].isHidden(options=op.get(name, {})), self._fieldOrder)
def submitFieldNames(self, optionSet={}):
return filter(lambda name, self=self, op=optionSet:
self._fields[name].isSubmit(options=op.get(name, {})), self._fieldOrder)
def field(self, fieldName):
return self._fields[fieldName]
def fields(self):
return self._fields
def name(self):
return self._name
def renderMethodName(self):
return self._renderMethod
def htStartForm(self, requestFields, defaults, optionSet,
includeHiddenFields=False):
"""Returns the beginning <form ...> part of a form.
Also returns the HTML for any hidden fields in the form."""
if self._enctype:
encString = ' enctype="%s"' % self._enctype
else:
encString = ''
formString = '''<form action="%s" method="%s" name="%s"%s>
<input type="hidden" name="_formID_" value="%s">\n''' % \
(self._handlerServletURL, self._method, self._name,
encString, self.formID())
if includeHiddenFields:
return formString + self.htHiddenFields(requestFields, defaults,
optionSet)
return formString
def htHiddenFields(self, requestFields, defaults, optionSet):
result = []
for fieldName, field in self._fields.items():
if field.isHidden(options=optionSet.get(fieldName, {})):
result.append(field.html(optionSet=optionSet,
defaults=defaults,
requestFields=requestFields))
return string.join(result, '\n')
def htEndForm(self, defaults, optionSet):
return '</form>\n'
def mutable(self):
"""This is the only way to modify a form definition"""
return MutableFormDefinition(self._handlerServletURL,
self._renderMethod,
self._fields,
self._fieldOrder,
self._submitFields,
self._formValidators,
self._errorFormatter,
self._method,
self._enctype,
self._name)
def validateConvert(self, request):
allGood = True
errors = {}
data = {}
methodPass, invokeAsFunction, noneAsDefault = None, False, False
for fieldName, field in self._fields.items():
good, value = field.attemptConvert(request)
if good:
data[fieldName] = value
if field.isSubmit() and value:
methodPass = field.methodToInvoke()
invokeAsFunction = field.invokeAsFunction()
noneAsDefault = field.noneAsDefault()
assert not field.suppressValidation(), "Uh oh, validation didn't
get suppressed like promised"
else:
allGood = False
errors[fieldName] = value
for formValidator in self._formValidators:
if not allGood and not formValidator.validatePartialForm():
continue
formErrors = formValidator.validate(data)
if not formErrors:
continue
allGood = False
if type(formErrors) is type(""):
formErrors = {"form": formErrors}
assert type(formErrors) is type({}), \
"form validators should return a string or dictionary"
for fieldName, errorMessage in formErrors.items():
if errors.has_key(fieldName):
if type(errors[fieldName]) is not type([]):
errors[fieldName] = [errors[fieldName]]
errors[fieldName].append(errorMessage)
else:
errors[fieldName] = errorMessage
return allGood, errors or data, methodPass, invokeAsFunction, \
noneAsDefault
class MutableFormDefinition(FormDefinition):
"""A FormDefinition that can be changed. Create with .mutable()
from a real FormDefinition."""
def __init__(self, handlerServletURL, renderMethod,
fieldDict, fieldOrder, submitFields,
formValidators, errorFormatter, method, enctype, name):
self._handlerServletURL = handlerServletURL
self._renderMethod = renderMethod
self._fields = fieldDict.copy()
self._fieldOrder = fieldOrder
self._submitFields = submitFields.copy()
self._formValidators = formValidators
self._errorFormatter = errorFormatter
self._method = method
self._enctype = enctype
self._name = name
self._serial = generateSerial()
MutableFormDefinitionStore[self._serial] = self
def formID(self):
return self._name
#return 'dynamic_%s_%06i' % (self._name, self._serial)
def addField(self, field, order=None):
self._fields[field.name()] = field
if not self._enctype and field.preferedEnctype():
self._enctype = field.preferedEnctype()
if field.isSubmit():
self._submitFields[field.name()] = field
if order is None:
self._fieldOrder.append(field.name())
else:
self._fieldOrder.insert(order,field.name())
def removeField(self, fieldName):
if self._fields[fieldName].isSubmit():
del self._submitFields[fieldName]
del self._fields[fieldName]
self._fieldOrder.remove(fieldName)
def replaceField(self, field):
self._fields[field.name()] = field
if not self._enctype and field.preferedEnctype():
self._enctype = field.preferedEnctype()
if field.isSubmit():
self._submitFields[field.name()] = field
FormSerialLock = threading.Lock()
FormSerial = 0
MutableFormDefinitionStore = {}
def generateSerial():
global FormSerialLock, FormSerial
FormSerialLock.acquire()
FormSerial = FormSerial + 1
serial = FormSerial
FormSerialLock.release()
return serial
def invokeFunctionWithDict(func, dict, noneAsDefault = False):
sig = Signature(func)
dict = dict.copy()
args = sig.ordinary_args()
defaults = sig.defaults()
a = [] # position args
kw = {} # keyword args
for arg in args:
if not dict.has_key(arg):
if not defaults.has_key(arg):
raise TypeError, "function argument name not contained in
FormDefinition: %s" % arg
else:
if defaults.has_key(arg):
if dict[arg] is not None or not noneAsDefault:
kw[arg] = dict[arg]
del dict[arg]
else:
a.append(dict[arg])
del dict[arg]
if sig.special_args().has_key('keyword'):
kw.update(dict)
else:
assert not dict, "function does not use arguments from FormDefinition: %s" %
dict.keys()
apply(func, a, kw)