One form for multiple tables

376 views
Skip to first unread message

annet

unread,
Mar 2, 2011, 1:06:20 PM3/2/11
to web2py-users
This example is taken from the web2py manual.

model:

db.define_table('client',
Field('name'))
db.define_table('address',
Field('client',db.client,writable=False,readable=False),
Field('street'),Field('city'))


controller:

def register():
form=SQLFORM.factory(db.client,db.address)
if form.accepts(request.vars):
id = db.client.insert(**db.client._filter_fields(form.vars))
form.vars.client=id
id = db.address.insert(**db.address._filter_fields(form.vars))
response.flash='Thanks for filling the form'
return dict(form=form)


Is it possible to pre-populate a form like this and then use update
instead of insert to update the records in the tables?

Kind regards,

Annet.

Richard Vézina

unread,
Mar 2, 2011, 1:54:18 PM3/2/11
to web...@googlegroups.com
See keepvalues in book, it should help with this objective...

Richard

DenesL

unread,
Mar 4, 2011, 11:59:14 AM3/4/11
to web2py-users
Hi Annet,

I believe you want something like this:

def multitable_form_update():
last=0
if request.args:
last=request.args[0]
# retrieve next 2 addresses
addrs=db(db.cli_addr.id>last).select(limitby=[0,2])
if addrs:
addr=addrs[0]
curr=addr.id
# set defaults to be shown on form
db.client.name.default=db.client[addr.client].name
db.cli_addr.street.default=addr.street
db.cli_addr.city.default=addr.city
else: # show EOF msg and loop
session.flash='no more addresses on file'
redirect(URL(request.action))
# set client to read only
db.client.name.writable=False
form=SQLFORM.factory(db.client,db.cli_addr)
# add link to next
form[0][-1][1].append(A("Skip to
Next",_href=URL(request.action,args=curr)))
if form.accepts(request.vars):
# update record and redirect
addr.update_record(**db.cli_addr._filter_fields(form.vars))
session.flash='record updated'
redirect(URL(request.action,args=last))
return dict(form=form)

annet

unread,
Mar 5, 2011, 11:32:34 AM3/5/11
to web2py-users
Hi Denes,

> I believe you want something like this:

That's exactly what I wanted, thanks!


Kind regards,

Annet.
Reply all
Reply to author
Forward
0 new messages