Web2py: Access row from custom widget

365 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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
    ...
0
On

The widget method itself only receives the field and value arguments, however, when you define the widget object you can add more arguments. Consider

In widget code

Class CustomWidget():
    def __init__(self, custom_arg_1, custom_arg_2): # Name them as needed
        self.custom_arg_1 = custom_arg_1
        self.custom_arg_2 = custom_arg_2

    def widget(field, value):
        if self.custom_arg_1 == self.custom_arg_2:
            return "Something helpful"
        else:
            return "Something else"

Then in your controller

from somewhere import CustomWidget

def this_uses_custom_widget():
    widget_with_args = CustomWidget(3,4) # Pass whatever you need there
    db.table.field.widget = widget_with_args.widget

Or, if those arguments are more global, you can declare the widget in the model.