Search code examples
web2pycustom-widgets

Web2py: Access row from custom widget


In web2py custom widgets get field description and value as arguments, while represent functions get value and table row. Is it possible to pass row to a custom widget function? I need to access other columns of the same row. I use rows inside SQLForm.smartgrid, so I don't have much control in this situation.


Solution

  • Assuming this is for dealing with SQLFORM.smartgrid update forms, you can try something like the following trick:

    def show_grid():
        if 'edit' in request.args:
            db.mytable.myfield.record = db.mytable(request.args(-1))
        return dict(grid=SQLFORM.smartgrid(db.mytable))
    

    The above code adds a "record" attribute to the field object (which will get passed to the widget, where you can then extract the record from the field object). Grid/smartgrid "edit" links include the record ID as the last URL arg, which is accessed via request.args(-1) above.

    In your custom widget code:

    def mywidget(field, value):
        record = field.record  # here you have the whole record
        ...