How do I use dynamic fields in Formlib?
In order to benefit the most from the formlib machinery, one should avoid subclassing form.EditForm? (as it would require you to also setup an adapter for your form field). The following code shows what's involved in having a custom field inside your form. :
from zope.formlib import form
from zope.schema import TextLine
class TestForm(form.PageForm):
my_field_name = 'something'
def __init__(self, context, request):
super(TestForm, self).__init__(context, request)
self.form_fields = form.Fields(TextLine(__name__=self.my_field_name, title=u"Test Field"))
def setUpWidgets(self, ignore_request=False):
name = self.name
self.widgets = form.setUpWidgets(
self.form_fields, self.prefix, self.context, self.request,
data={self.my_field_name:SOME_VALUE},
ignore_request=ignore_request)
@form.action(label=_("Submit"))
def handleSubmitAction(self, action, data):
#do something relevant to you here
... --kevingill, Thu, 29 Nov 2007 16:19:55 +0000 reply
I have found this example really useful.
However, when submitting a form you generally want to validate the input. Can someone update this example to show us how to use invariants and how to return an Invalid exception from the handleSubmitAction.
I have only been able to edit the validate() method, but this is less than optimal.
... --Tiberiu Ichim, Fri, 30 Nov 2007 10:07:06 +0000 reply
kevingill: have you tried adding constraints to the fields defined for self.form_fields, as you would normally do with a regular interface? The validation is typically done before the action handler (handleSubmitAction in this case) is executed.
