Random notes from mg

a blog by Marius Gedminas

Marius is a Python hacker. He works for Programmers of Vilnius, a small Python/Zope 3 startup. He has a personal home page at http://gedmin.as. His email is marius@gedmin.as. He does not like spam, but is not afraid of it.

Fri, 14 Jul 2006

Easy Zope 3 forms with formlib: add forms.

A short tutorial of zope.formlib.

Here's how you create an add form for a notional content object Fruit:

# This is the mypackage.browser module
from zope.formlib import form

from mypackage.interfaces import IFruit
from mypackage.fruit import Fruit

class FruitAdd(form.AddForm):

    form_fields = form.Fields(IFruit)

    def create(self, data):
        # In our example Fruit class has an __init__
        # that accepts all the fields as keyword arguments
        return Fruit(**data)

Here's how you register it in ZCML

<browser:page
    for="zope.app.container.interfaces.IAdding"
    name="mypackage.Fruit"
    class="mypackage.browser.FruitAdd"
    permission="zope.ManageContent"
    />

<browser:addMenuItem
    title="Fruit"
    class="mypackage.fruit.Fruit"
    view="mypackage.Fruit"
    permission="zope.ManageContent"
    />

Here's a zip file with full working code: formlib-adding-example.zip

Update: changed the link to point to the up-to-date version of zope.formlib.

Update: Martijn Pieters shows how to use the handy applyChanges function when you do not have a constructor that takes all the parameters.

posted at 18:50 | tags: | permanent link to this entry | 0 comments

Name (required)


E-mail (will not be shown)


URL


Comment (some HTML allowed)