Dynamic Dropdown Items

Hi,

I have a question that I am sure is easily answered, but I could not find the answer on here. I would like to have a pair of dropdowns where the items for the second depend on the selected value of the first.

Here is the portion of code that I have to try to accomplish this:

   def drop_down_1_change(self, **event_args):
      """This method is called when an item is selected"""
      years = ratingsDict[self.drop_down_1.selected_value].keys()
      
      self.drop_down_3.items = []
      for year in years:
        self.drop_down_3.items.append(year)
        
      return self.drop_down_3.items

ratingsDict is a nested dictionary, and years should be a list of the keys within the dictionary for the selected value. I think this code should return the correct list of keys to become the items for each selected value. I do not receive an error message. The items just simply do not appear.

I’m sure this is an easy fix and that I am just missing something simple. Please let me know if you have any ideas.

Hi @walter.anson.327

Yes, there is an easy fix!

The DOM elements representing the DropDown are updated when the DropDown’s assignment operator (=) is called. append doesn’t call the assignment operator, so you need to make a trivial call to the assignment operator when you want to update the DOM:

self.drop_down_3.items = self.drop_down_3.items

Here’s a quick test app showing that working:

https://anvil.works/build#clone:VL7P55EZUNZD6IRI=U5CIBV3VQBUQIN2HK2B2W3EV

I’ll add this to the reference docs. Thanks for getting in touch, posts like this help us flush out corner cases that need documenting.

EDIT: To make things a bit simpler, you can replace the entire loop with self.drop_down_3.items = years.

1 Like

Hi @shaun - while working with my students we noticed erroneous behaviour in tutorials Storing and Displaying Data tutorial and Multi-User Apps. The code which doesn’t work as it should is for example:

new_row = app_tables.reminders.add_row(description=self.new_reminder_box.text, done=False)
l = self.repeating_panel_1.items + [new_row]
    
self.repeating_panel_1.items = l

The solution is similar to the tip you gave to @walter.anson.327. The code can be replaced by

app_tables.reminders.add_row(description=self.new_reminder_box.text, done=False)self.repeating_panel_1.items = app_tables.reminders.search()

For beginners, the tutorials are a bit misleading at that point.

1 Like

Thanks for letting us know. Ideally I would cleverly edit the video to fix the error but I think it’s at a part that’s hard to edit. I’ll add a warning to the text for now.