[Zope] Re: Simple worked example for ZPT forms

Evan Simpson evan@4-am.com
Tue, 03 Dec 2002 16:47:54 -0600


Sam Hunting wrote:
> Can anyone point me to a complete worked example? From the request form,
> through the scripted action, to the response.

Here's a quick sample of the pattern I usually use.  The Script controls 
the action:

## Script (Python) "formDemo"
##parameters=data=None
##
form = container['formDemo.zpt']
if data is None:
     return form()

errors = {}
if not data.name.strip():
     errors['name'] = 'Name is required'
if data.ssn.strip():
     if len(data.ssn.strip()) < 9:
         errors['ssn'] = 'SS # must be nine digits'
else:
     errors['ssn'] = 'SS # is required'

if errors:
     return form(errors=errors)

# Do something with the valid data

...and the Page Template displays the form:

<html>
   <body>
     <form method="POST" tal:attributes="action request/URL"
      tal:define="data request/form/data | nothing">

<div>Name: <input name="data.name:record"
        tal:attributes="value data/name | nothing" />
<span tal:replace="options/errors/name | nothing">Error</span>
</div>

<div>SS#: <input name="data.ssn:record"
        tal:attributes="value data/ssn | nothing" />
<span tal:replace="options/errors/ssn | nothing">Error</span>
</div>

<div><input type="submit" value="Submit" /></div>

     </form>
   </body>
</html>


Cheers,

Evan @ 4-am