What I’m trying to do:
How to display a table with Labels and Textboxes, when I don’t know the number of columns, or what the column names will be?
E.g.
A user specifies any set of animals categories (dog/cat/parrot/anything), and there are specific types of each animal:
dog = [d1, d2, d3, d4]
cat = [c1, c2, c3, c4]
mouse = [m1, m2, m3, m4]
My program then generates combinations (e.g. [d1, c3, m4]) and the user specifies how to evaluate it (e.g. ‘ranking’). So a label for each component (d1, c3, m3) should be created programatically and displayed under the correct column, while the ranking should be a textbox that writes back to the ‘combinations’ datatable.
Currently, the column headers and column names are not aligned, and the text box does not write back to my datatable.
What I’ve tried and what’s not working:
Read the docs, but this only works if I know the column name: Anvil Docs | Data Bindings
Dynamic data bindings post, but here the components (e.g. labels) were added with the drag-and-drop, not programatically: About data binding with custom components
Generate text boxes with code, I tried this but couldn’t get the headers to align with the data input textbox: Want to be able to generate x number of TextBoxes
Code Sample:
class ItemTemplate1(ItemTemplate1Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
data = self.item # a dictionary
# Dynamically create components for each key-value pair
for key, value in data.items():
if key == 'ranking': # will do this check differently in my actual code
# Create a TextBox for editable 'c5205'
textbox = anvil.TextBox(text=value)
# Optionally, bind the TextBox's lost_focus event to save changes
textbox.tag = key # Use tag to identify the column
# textbox.set_event_handler('lost_focus', self.textbox_lost_focus)
self.flow_panel_1.add_component(textbox)
else:
# For non-editable fields, just display the value
label = anvil.Label(text=f"{key}: {value}")
self.flow_panel_1.add_component(label)
def textbox_lost_focus(self, sender, **event_args):
edited_value = sender.text
column_name = sender.tag
print(f"Edited {column_name}: {edited_value}")
Clone link: Anvil | Login