Dynamically change field value in web2py sqlform

762 Views Asked by At

I want to generate a sqlform.grid using a database table defined as:

db.define_table('ClientInfo',
            Field('HostID', type='text', label='HostID'),
            Field('MACAddress', type='text',  label='MACAddress'),
            Field('MachineName', type='text', label='MachineName'),
            Field('IPAddress', type='text',  label='IPAddress'),
            Field('TimeOffset', label='TimeOffset'),
            Field('RunningAs', type='text',  label='RunningAs'),
            Field('SystemVersion', type='text',  label='SystemVersion'),
            Field('OSType', type='integer', label='OSType'),
            Field('AgentVersion', type='text', label='AgentVersion'),
            Field('FirstCheckin', type='datetime',  label='FirstCheckin'),
            Field('LastCheckIn', type='datetime', label='LastCheckIn')
           )

The OSType field is an enumerator-type integer and as such I'd like to change it prior to display so that it identifies the OS type not by the integer but by a string (e.g. 0 = Windows XP, 1 = Windows 2012, and what not). Is there an easy way to do this?

1

There are 1 best solutions below

3
On

To change the display in the grid as well as read-only forms, use the represent attribute of the field (see the end of this section of the documentation).

You can also add an IS_IN_SET validator, which by default will result in a select widget in any forms (e.g., the grid create and edit forms). You can pass a dictionary or list of tuples to the validator to specify a set of labels to associate with the values (see the end of this section of the documentation):

OS_TYPES = {
    0: 'Windows XP',
    1: 'Windows 2012',
    ...
}

db.define_table('ClientInfo',
    ...
    Field('OSType', type='integer',
          requires=IS_IN_SET(OS_TYPES), # Results in select widget in forms.
          represent=lambda v, r: OS_TYPES[v]), # Sets display value in grid.
    ...)