Hi everyone
I need some help with how to reference a nested dynamically created button so that it runs a function when clicked.
For context, it’s for an idea voting app that people can use for voting ideas up and down. It runs through a data table which contains an ‘Idea’ column, and a ‘Score’ column.
So far, upon init, the app runs through the table and, within a Linear Panel, dynamically generates a Column Panel (card) for each idea, and within each card, dynamically generates labels to show the content of the idea, and buttons for voting up and down. See the image:
What I need help with
I want to set up event handlers to tell the buttons upon being clicked that they should run a function, but I can’t seem to work out how to correctly reference them, most likely following on from them being dynamically generated within other dynamically generated containers.
I have tried getting hold of the buttons using ‘self.linear_panel_1.idea_card.upButton’, which is their nested hierarchy, but that causes this error:
AttributeError: ‘LinearPanel’ object has no attribute ‘idea_card’
So it’s like the linear panel can’t see the Column Panel ‘idea_card’ inside it, even though it has already been dynamically created.
I’ve looked at the docs for event handlers (Anvil Docs | Anvil Components) but can’t seem to apply this here.
Code (simplified to show issue):
class Main_page(Main_pageTemplate):
def __init__(self, **properties):
self.init_components(**properties)
# Voting board
tableData=anvil.server.call('getideas')
def vote_button_click(self, **event_args):
print('test ok') # This is what I want to be run when the upButton is clicked
for i in range(0,len(tableData)): # This is the loop which displays the ideas
idea_card = ColumnPanel(role='card')
self.linear_panel_1.add_component(idea_card) # ColumnPanel added within LinearPanel
...
upButton = Button(text='+1',font_size=12,background='Blue',foreground='white')
idea_card.add_component(upButton) # Button created
### What should this last line be to make the button run vote_button_click upon being clicked?
self.linear_panel_1.idea_card.upButton.add_event_handler('click', self.vote_button_click)
Some more code which shows the same issue:
upButton = Button(text='+1',font_size=12,background='Blue',foreground='white')
idea_card.add_component(upButton)
idea_card.upButton.add_event_handler('click', self.vote_button_click)
upButton was just added dynamically to idea_card (dynamically generated Column Panel), but the last line causes this error:
'AttributeError: ‘ColumnPanel’ object has no attribute ‘upButton’
https://anvil.works/build#clone:7LXMBIIZSMKQNPY7=FJ5D5GSZK6FHRHMJHHJLJIQ6