Version 9 (modified by 14 years ago) ( diff ) | ,
---|
IS_ONE_OF Validator
(For large lookup tables use IS_ONE_OF_EMPTY)
The IS_ONE_OF() validator is a custom version of web2py's IS_IN_DB() for foreign key lookups in a key table. In forms, the respective field will be rendered as a drop-down field.
Unlike IS_IN_DB, the IS_ONE_OF validator is deletion status sensitive, i.e. records in the key table that are flagged as 'deleted' will be ignored.
Furthermore, it is possible to filter the key records by a type field (which should be int) for certain options.
Usage:
db.table.field.requires = IS_ONE_OF(db, "keytable.keyfield", represent, filterby="fieldname", filter_opts=options)
- keytable = Name of the key table
- keyfield = Name of the key field
- represent = how to build the option label (in drop-downs in forms) from the key entry, one of the following:
- string template, e.g.
"%(first_name)s %(last_name)s"
- list or tuple of field names, e.g.
('first_name', 'last_name')
- function or lambda, e.g.
lambda r: "%(first_name)s %(last_name)s" % dict(r)
- string template, e.g.
- filterby="fieldname" = the type field (int) to filter for
- filter_opts="options" = a list or tuple of allowed values for the filterby-field
Note:
- Without represent and if no 'name' field can be detected in the table, the keyfield itself will be used as option label.
- If filterby is specified, the drop-down fields get sorted by this field.
- IS_ONE_OF can be cascaded through IS_NULL_OR to include empty selection
Example:
... db.Field("pr_pe_id", db.pr_pentity), ... db[table].pr_pe_id.requires = IS_NULL_OR(IS_ONE_OF(db, "pr_pentity.id", # key table=pr_pentity, key field=id shn_pentity_represent, # function to represent a pr_pentity entry as string filterby="opt_pr_pentity_class", # type field in the pr_pentity table filter_opts=(1,), # select only entries with opt_pr_pentity_class in (1,) (select only persons) orderby="pr_pentity.id" # NB Need explicit orderby, otherwise it orders by all fields! ))