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.
Web2py: Access row from custom widget
335 views Asked by user174916 At
2
There are 2 answers
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.
Assuming this is for dealing with
SQLFORM.smartgrid
update forms, you can try something like the following trick: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: