Write client-side Python
Step 1: Run a Data Table search
Add this code underneath the import statements on your ‘ArticleEdit’ Form:
categories = [ (cat['name'], cat) for cat in app_tables.categories.search() ]
This creates a list of 2-tuples:
[ ("First category name", <first_row_from_table>), ..., ("Final catgegory name", <final_row_from_table>) ]
The first element of each tuple is what will be displayed in the DropDown box. The second element of the tuple becomes the
selected_value property of the DropDown if that option is selected.
Step 2: Configure your Data Table permissions.
By default, client-side code in Anvil doesn’t have permission to access Data Tables. Go to your ‘categories’ Data Table and change the permissions to allow Forms ‘search’ access:
It’s safe to do so in this case, because the ‘categories’ Data Table contains no sensitive information - it’s just a simple list of strings.
Step 3: Populate your dropdown
To display our list of categories in the DropDown, we set the
items property of our DropDown to the
categories list we just defined. Go back to your ‘ArticleEdit’ Form and add this line to the
# Any code you write here will run when the form opens. self.category_box.items = categories
Your ‘ArticleEdit’ Form should now look like this:
from anvil import * import anvil.tables as tables import anvil.tables.query as q from anvil.tables import app_tables categories = [(cat['name'], cat) for cat in app_tables.categories.search()] class ArticleEdit(ArticleEditTemplate): def __init__(self, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) # Any code you write here will run when the form opens. self.category_box.items = categories
Step 4: Test that it works
To test that it works, set the ArticleEdit Form as the Startup Form by clicking on the down-arrow next to the ArticleEdit form in the panel on the left. The lightning bolt icon will appear next to ArticleEdit if you’ve done it successfully.
Now run the app. You should see the ArticleEdit Form running, and the dropdown should be populated with your article categories:
Remember to set Homepage back as the Startup Form when you’ve finished.
We’ve written the first piece of client-side Python code - we’ve made the ArticleEdit Form get its list of categories from the database when the app starts up.
In Chapter 4, we’ll enable users to add articles to the database.