web2py

Can I use a virtual field to display the value of a linked table in web2py?


I will try to make my question clear with an example :-)

Let's say I want to display a comments text about the residual value of cars, only based on the car brand and the year it was build. The table 'ResidualValueInfo' would contain a matrix with cars, the build year and the corresponding text to be shown.

I would have following model:

db.define_table('brand',
                Field('name',type='text'),
                Field('info',type='text'),
                Field('logo')
                )

db.define_table('age',
                Field('buildYear',type='integer'),
                Field('backgroundInfoAboutThatYear',type='text')
                )

db.define_table('ResidualValueInfo',
                Field('brand','reference brand'),
                Field('age','reference age'),
                Field('comment',type='text')
                )

Finally I would create the 'cars' table where I would store the inputs my users:

db.define_table('car',
                Field('owner',type='text'),
                Field('color',type='text'),
                Field('brand','reference brand'),
                Field('age','reference age'),
                )

My input form would look like this:

def addNew():
    form = SQLFORM(db.car)
    if form.process().accepted:
        response.flash = T('car added')
        redirect(URL('view'))
    else:
        response.flash = T('Please complete the form')
        return locals()

But whilst filling in the form (and thus selecting a brand and an age), I would already want to show the 'comments' field of the linked ResidualValueInfo table even before hitting the save button...

HEEEEEELP :-)


Solution

  • I don't believe there is any magical built-in way to do what you want. And this is a tricky problem which is going to require an AJAX call to get the data after the selection.

    The big idea is this:

    1. Attach event listeners to the brand and age controls in the form (see here). I would probably do this after the page has loaded.
    2. When they trigger, issue an AJAX call to a controller that can query the database to find the comment based on the selected age and brand. There are multiple ways to do this - here is a generic one and here is a web2py ajax call.
    3. Update your form with the returned data.

    This is not a trivial problem so it will require some thinking. web2py makes a lot of things easy - but not that sort of thing.