我有一个看起来很像web2py-docs中的样本:
http://web2py.com/books/default/chapter/29/07/forms-and-validators#onvalidation
模型/ db.py:
db.define_table('numbers',
# Field('user_id', 'reference auth_user'),
Field('user_id', 'integer'),
Field('b', 'boolean'),
Field('c', 'integer')
# db.numbers.user_id.requires = IS_IN_DB(db, db.auth_user.id)
db.numbers.user_id.writable = db.numbers.user_id.readable = False
db.numbers.id.writable = db.numbers.id.readable = False
控制器/ default.py:
def my_form_processing(form):
if not form.vars.b:
form.vars.c = None
# @auth.requires_login()
def insert_numbers():
# record = db(db.numbers.user_id==auth.user_id).select().first()
record = db(db.numbers.user_id=1).select().first()
db.numbers.c.show_if = (db.numbers.b == True)
form = SQLFORM(db.numbers, record)
if form.process(onvalidation=my_form_processing).accepted:
session.flash = 'record inserted'
redirect(URL())
return dict(form=form)
但添加了一些“魔力”:
这很有效(如果'b'为false,则c的数据库值设置为NULL)但这里是catch:
如何清除字段'c'的表单值? (如果我只是在'b'为False时重新加载页面,'c'将是一个空字段。此问题仅在提交时出现。)
有人可以帮我吗?
答案 0 :(得分:0)
如果您的目标是简单地有条件地删除该变量,那么可以采用以下方法:
def insert_numbers():
record = db(db.numbers.user_id=1).select().first()
db.numbers.c.show_if = (db.numbers.b == True)
form = SQLFORM(db.numbers, record)
if form.validate(message_onsuccess = 'record inserted'):
if not form.vars.b:
del form.vars.c
db['numbers'].insert(**form.vars)
db.commit() # just to be safe
redirect( URL(...) )
return dict(form=form)