wiki:S3/S3ReusableField

Version 17 (modified by Fran Boon, 10 years ago) ( diff )

--

Developer Guidelines | S3ReusableField

S3ReusableField

S3ReusableField is a DRY helper class for re-usable Field definitions.

Define a S3ReusableField

A S3ReusableField is to be 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 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
                        ...)

Note: If the S3ReusableField contains the sortby attribute, then a FieldS3 instance is generated instead of Field

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")), # replaces the label attribute by T("Reporter")
                        ...)

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
                        ...)

DeveloperGuidelines

Note: See TracWiki for help on using the wiki.