Let's not forget about SQLFORM.factory either. This lets you create a
SQLFORM based on a virtual table that you create as an argument to
SQLFORM.factory. For example, I used this code to provide edit capabilities
when editing time clock entries for an app I'm writing. It includes form
validation, and I wrote a module that handles the actual db update. When you
see "timeclock.edit_entry(....)", this is just handing off the form
variables to the module, which performs extra validation on the data before
committing it to the db. NOTE: All of this code is inside my "def edit():"
function.
def validate_form(form):
users = [auth.user.id]
for user in user_security.get_subordinates(auth.user):
users.append(user.auth_user.id)
if int(form.vars.auth_user) not in users:
form.errors.adjusted_start = "You do not have permission to
modify this person's time clock."
if not request.args(0): raise HTTP(400, 'Timeclock ID not found')
timeclock_id = request.args(0)
timeclock_entry = db(db.timeclock.id==timeclock_id).select().first()
if timeclock_entry is None: raise HTTP(400, 'Timeclock ID not found')
form = SQLFORM.factory(
Field('adjusted_start', 'datetime', requires=IS_NOT_EMPTY()),
Field('adjusted_end', 'datetime'),
Field('reason', 'text', requires=IS_NOT_EMPTY()),
Field('auth_user', db.auth_user, readable=False, writable=False),
hidden = {'id': timeclock_id, 'auth_user':
timeclock_entry.auth_user.id}
)
form.vars.auth_user = timeclock_entry.auth_user.id
form.vars.adjusted_start = timeclock_entry.adjusted_start
form.vars.adjusted_end = timeclock_entry.adjusted_end
if form.accepts(request.vars, session, keepvalues=True,
onvalidation=validate_form(form)):
row_id = timeclock.edit_entry(auth.user, timeclock_entry,
form.vars.reason, form.vars.adjusted_start, form.vars.adjusted_end)
if isinstance(row_id, str):
response.flash = row_id
else:
redirect(URL('index'))
return dict(form=form, timeclock_entry=timeclock_entry, history=history)