> > 2) Since we're building the form with values from the DB in the
> > beginning of the function, then updating the DB, then returning the
> > form, the view gets a stale copy of the form. I guess you could solve
> > this with a redirect if form.accepts() is true? Seems hackish...
>
> Can you provide a text case?
>
more specifically, form.accepts(request.vars,session, keepvalues=True)
fixed the problem I was having (keepvalues=True). My old index
controller looked like:
def index():
table = TABLE()
table.append(TR(TH("Image"), TH("Description"), TH("need")))
items = db().select(db.Item.ALL)
for item in items:
img_location = URL(r=request, f='download', args=item.image)
if item.image:
img = IMG(_width="100px", _src=img_location,
_alt=item.description)
else:
img = "No Image"
chk = INPUT(_type='checkbox', _name='need_%s' % item.id,
value=item.need)
junk = INPUT(_type='hidden', _name='need_%s' % item.id,
_value='False')
table.append(TR(img,A(item.description, _href=URL(r=request,
f='details', args=item.id)),chk,junk))
form = FORM(table,INPUT(_type='submit', _value='Update'))
if form.accepts(request.vars,session, keepvalues=True):
for k,v in request.vars.items():
if k.startswith('need_'):
id = k.split('_')[-1]
item = db(db.Item.id == int(id)).select()[0]
item.update_record(need=('on' in v))
#redirect(URL(r=request, f=index))
return dict(form=form, vars=form.vars)
Which leads me to my next question: Which is the preferred way to do
this? The above way I just call {{=form}} in the view. My current
way is:
def index():
for k,v in request.vars.items():
if k.startswith('need_'):
id = k.split('_')[-1]
item = db(db.Item.id == int(id)).select()[0]
need=('on' in v)
item.update_record(need=('on' in v))
response.flash = "Form Saved"
items = db().select(db.Item.ALL)
return dict(items=items)
and then I build the form with html in the view. Which is better?
Sorry for all the questions :/
Thanks,
Rob