wiki:S3/S3ReusableField

Version 2 (modified by Dominic König, 11 years ago) ( diff )

--

S3ReusableField

S3ReusableField is a DRY helper class to pre-define fields in tables.

Define a S3ReusableField

An S3ReusableField is defined like a normal Field (though outside Table definition):

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, it 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 field name and any of the field attributes in the S3ReusableField 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
                        ...,
                        migrate=migrate)

Deactivate IS_NULL_OR/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)

DeveloperGuidelines

Note: See TracWiki for help on using the wiki.