Personal tools
You are here: Home Documentation How-Tos Customising Fields in Grok AddForm and EditForm

Customising Fields in Grok AddForm and EditForm

This How-to applies to: 0.12, 0.11, 0.10
This How-to is intended for: Developer

How does one customise attributes of an auto generated Grok Form.

Purpose

Using grok.Addform and grok.EditForm it's very easy to generate an HTML form out of a Zope 3 schema definition. You will typically declare the schema(s) that your Grok Model instances implement in the Model class.

You can customize your (Zope Page) Template and write the HTML form by hand, but it´s also possible to modify the Python in your Form class and autogenerate the HTML.

Prerequisities

Just set up some Forms in Grok. Described in this HowTo.

Step by step

Example: you want a custom label for code field only.

class IFaculty(Interface):
    code = schema.TextLine(title=u"Code")
    name = schema.TextLine(title=u"Name")
    title_prefix = schema.TextLine(title=u"Prefix")

class Faculty(grok.Form):
    form_fields = grok.AutoFields(IFaculty)

    def setUpWidgets(self, ignore_request = False):
        super(Faculty, self).setUpWidgets(ignore_request)
        self.widgets['code'].label = u'newcode label'

Further information

The grok.AddForm and grok.EditForm build upon zope.formlib for form generation. Form instances contain a widgets attribute which is a dictionary containg all field widgets. The setupWidgets method of a form is responsible for creating this attribute. You can override this method in your form to customize the widgets after they have been set-up. You can do this by first calling the parent method in zope.formlib.form.EditFormBase to perform the default widget set-up, and then modify the widgets as necessary.

Don't do this:

class Edit(grok.AddForm):
    form_fields = grok.AutoFields(Friend)
    form_fields['name'].field.title = u'Fill in your name'
    form_fields['name'].field.default = u'My name'

Here you are not modifying the name field for the Edit form, but are directly modifying the IFaculty schema definition.

see also:

Automatic Form Generation
Grok supports automatic form generation by working with zope.interface, zope.schema and zope.formlib. This how-to will show you how to create an application that uses this feature and also how to use some more advanced widgets than the formlib defaults.

Field manipulation vs. widget manipulation

Posted by whit morriss at Jun 13, 2008 09:32 AM
it might be helpful to specify the difference between omitting and manipulating fields since it looks very similar to setting up widgets and may be seen as part of the same "getting my form to display right" set of tasks.