| Version 7 (modified by , 15 years ago) ( diff ) |
|---|
Table of Contents
S3ReusableField
S3ReusableField is a DRY helper class for re-usable Field definitions.
Define a S3ReusableField
A S3ReusableField is defined like a normal Field (though outside any Table definitions):
person_id = S3ReusableField("person_id", db.pr_person,
sortby = ["first_name", "middle_name", "last_name"],
requires = IS_NULL_OR(IS_ONE_OF(db, "pr_person.id",
shn_pr_person_represent,
orderby="pr_person.first_name",
sort=True,
error_message="Person must be specified!")),
represent = lambda id: (id and \
[shn_pr_person_represent(id)] or [NONE])[0],
label = T("Person"),
comment = shn_person_id_comment,
ondelete = "RESTRICT",
widget = S3PersonAutocompleteWidget(request))
This definition does not create a Field instance, but just holds the parameters.
Use S3ReusableFields in Table Definitions
To use this in a Table definition, just call the S3ReusableField instance object to generate a Field instance:
resourcename = "mytable"
tablename = "%s_%s" % (module, resourcename)
table = db.define_table(tablename,
...,
person_id(), # inserts a Field("person_id") with the pre-defined parameters
...,
migrate=migrate)
Override Field Attributes
You can override the name and any attributes when generating the Field instance, by just re-specifying them:
resourcename = "mytable"
tablename = "%s_%s" % (module, resourcename)
table = db.define_table(tablename,
...,
person_id("reporter", # inserts a Field("reporter") with the attributes from person_id,
label=T("Reporter")), # but replaces the label attribute by T("Reporter")
...,
migrate=migrate)
Deactivate IS_EMPTY_OR
To deactivate a IS_NULL_OR (IS_EMPTY_OR) validator in the S3ReusableField when generating the Field instance, you can use the special attribute empty:
resourcename = "mytable"
tablename = "%s_%s" % (module, resourcename)
table = db.define_table(tablename,
...,
person_id(empty=False), # inserts the person_id Field, but removes IS_NULL_OR from .requires
...,
migrate=migrate)

