Forms with values in TurboGears

So 0.9a1 supports forms, that’s great. However, I found getting hold of suitable examples for use in the real world difficult. The examples all show how to create a form and display it, and also how to validate the information in the response. What they didn’t show, is how to get information into the form when it’s displayed.

So here is a quick sample showing how it’s done:

In your python code, you build up a dictionary of the field values:

class SomeFields(widgets.WidgetsDeclaration):
    name = widgets.TextField(validator=validators.NotEmpty)
    email = widgets.TextField(validator=validators.Email())

the_form = widgets.TableForm(fields=SomeFields(), submit_text="Post")

class Root(RootController):
    @expose(template=".templates.index")
    def index(self):
        values = {"name":"simon", "email":"me@there.com"}
        return dict(form=the_form, values=values)

Then in your kid template, you pass the values in to the form:

${form(action="submitForm", value=values)}

4 comments

  1. como podria poner los campos en columnas?
    si es que se puede…

    ejemplo:

    name _________ email____________

    y mas de un boton para submit?

  2. I was trying to figure out how to do this earier today. This works great; thanks!

  3. The ability to pre-populate columns in tg based on table structures is a widget which is definitely needed.
    1) Read table columns and defined attributes from sqlObject.
    2) Create Form Fields based on attributes
    3) Setup a config file where user can change attributes to form field values…

  4. Works great. Thanks.

    I was wondering if anyone know how to create custom form layout?

    So if my controller contains:
    class SomeFields(widgets.WidgetsDeclaration):
    name = widgets.TextField(validator=validators.NotEmpty)
    email = widgets.TextField(validator=validators.Email())

    the_form = widgets.TableForm(fields=SomeFields(), submit_text=”Post”)

    and in my template i would want to do something like:

    form.name
    form.email

    How would i do it?

    Thanks for your time!