| | 1 | [[TOC]] |
| | 2 | = S3ReusableField = |
| | 3 | |
| | 4 | S3ReusableField is a DRY helper class to pre-define fields in tables. |
| | 5 | |
| | 6 | == Define a S3ReusableField == |
| | 7 | |
| | 8 | An S3ReusableField is defined like a normal [http://web2py.com/book/default/chapter/06?search=Field#DAL,-Table,-Field Field] (though outside Table definition): |
| | 9 | |
| | 10 | {{{ |
| | 11 | person_id = S3ReusableField("person_id", db.pr_person, |
| | 12 | sortby = ["first_name", "middle_name", "last_name"], |
| | 13 | requires = IS_NULL_OR(IS_ONE_OF(db, "pr_person.id", |
| | 14 | shn_pr_person_represent, |
| | 15 | orderby="pr_person.first_name", |
| | 16 | sort=True, |
| | 17 | error_message="Person must be specified!")), |
| | 18 | represent = lambda id: (id and \ |
| | 19 | [shn_pr_person_represent(id)] or [NONE])[0], |
| | 20 | label = T("Person"), |
| | 21 | comment = shn_person_id_comment, |
| | 22 | ondelete = "RESTRICT", |
| | 23 | widget = S3PersonAutocompleteWidget(request)) |
| | 24 | }}} |
| | 25 | |
| | 26 | This definition does '''not''' create a Field instance, it just holds the parameters. |
| | 27 | |
| | 28 | == Use S3ReusableFields in Table Definitions == |
| | 29 | |
| | 30 | To use this in a Table definition, just call the S3ReusableField instance object to generate a Field instance: |
| | 31 | |
| | 32 | {{{ |
| | 33 | resourcename = "mytable" |
| | 34 | tablename = "%s_%s" % (module, resourcename) |
| | 35 | table = db.define_table(tablename, |
| | 36 | ..., |
| | 37 | person_id(), # inserts a Field("person_id") with the pre-defined parameters |
| | 38 | ..., |
| | 39 | migrate=migrate) |
| | 40 | }}} |
| | 41 | |
| | 42 | == Override Field Attributes == |
| | 43 | |
| | 44 | 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: |
| | 45 | |
| | 46 | {{{ |
| | 47 | resourcename = "mytable" |
| | 48 | tablename = "%s_%s" % (module, resourcename) |
| | 49 | table = db.define_table(tablename, |
| | 50 | ..., |
| | 51 | person_id("reporter"), # inserts a Field("reporter") with the attributes from person_id |
| | 52 | ..., |
| | 53 | migrate=migrate) |
| | 54 | }}} |
| | 55 | |
| | 56 | == Deactivate IS_NULL_OR/IS_EMPTY_OR == |
| | 57 | |
| | 58 | 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}}}: |
| | 59 | |
| | 60 | {{{ |
| | 61 | resourcename = "mytable" |
| | 62 | tablename = "%s_%s" % (module, resourcename) |
| | 63 | table = db.define_table(tablename, |
| | 64 | ..., |
| | 65 | person_id(empty=False), # inserts the person_id Field, but removes IS_NULL_OR from .requires |
| | 66 | ..., |
| | 67 | migrate=migrate) |
| | 68 | }}} |
| | 69 | |
| | 70 | ---- |
| | 71 | DeveloperGuidelines |