Grid/Form validation function inconsistency

39 views
Skip to first unread message

Tom Clerckx

unread,
May 22, 2025, 12:31:30 PM5/22/25
to py4web
I think this is worth mentioning in the documentation regarding the validation function of the grid/form (and/or make code-changes). 

In web2py:
In the validation function:
  • you could modify the values of the form vars 
  • you could add additional form vars

In py4web:
In the validation function:
  • You cannot add form vars
  • You cannot assign new values to the form vars
  • You can manipulate certain form vars (like a list)
  • In order to change/add elements in py4web that are stored in the database, one could use one of the DAL callbacks 
    • _before_insert 
    • _before_update
In general, I would say not to use the validation function to make changes to the form data.

See code sample below (note the remarks in the validation function)

### Model
table_test_two = db.define_table('test_two',
Field('name', 'string'),
Field('number', 'list:integer'),
)
db.commit()


### Controller
def sample_two_validate(form):
# --> This does not work in py4web - whereas it worked in web2py:
# (the name stays unchanged in py4web)
form.vars['name'] = "Hellow"
# --> This works both in py4web and web2py:
form.vars['number'].append(42)

@action("sample_two")
@action("sample_two/<path:path>")
@action.uses("generic.html")
def index(path=None):
# testtwo: test validation function
grid = Grid(path,
query=(db.test_two.id > 0),
validation=sample_two_validate
)
return dict(grid=grid)


Reply all
Reply to author
Forward
0 new messages