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 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 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 (unless overriden by orderby).
- IS_ONE_OF can be cascaded through IS_NULL_OR to include empty selection
Example:
db[table].pe_id.requires = IS_NULL_OR(IS_ONE_OF(db, "pr_pentity.pe_id", # key table=pr_pentity, key field=pe_id shn_pentity_represent, # function to represent a pr_pentity entry as string filterby="instance_type", # type field in the pr_pentity table filter_opts=("pr_person",), # select only entries with instance_type in ("pr_person",) (select only persons) orderby="pr_pentity.pe_id" # NB Need explicit orderby, otherwise it orders by all fields! ))