Chapter 3:
Write client-side Python

Let’s now populate the DropDown we added in Chapter 2 with a list of category names from the Categories Data Table. We’ll use Anvil’s search query operator to do this.

Step 2: Configure your Data Table permissions.

By default, client-side code in Anvil doesn’t have permission to access Data Tables. This is because any code that runs on the client will be accessible to users, and we want our Data Tables to be secure by default.

Our Categories Data Table doesn’t contain any secure information, so we can go ahead and make that table searchable from client code. Go to the Categories table and change the permissions to allow Forms ‘search’ access:

Changing the Data Table permissions to allow Forms to search the Categories table

Step 3: Populate your dropdown

To display our list of categories in the DropDown, we need to set the items property of our DropDown to the self.categories list we just defined. Go back to your ‘ArticleEdit’ Form and add this line to the __init__ method:

    # Any code you write here will run when the form opens.
    self.category_box.items = self.categories

The ‘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


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.categories = [(cat['name'], cat) for cat in app_tables.categories.search()]
    self.category_box.items = self.categories

Step 4: Test that it works

To test what we’ve built so far, we can run our app and try it out. Let’s first set the ArticleEdit Form to be the Startup Form by opening up the App Browser, clicking the three dots menu next to ‘ArticleEdit’ and selecting ‘Set as Startup Form’. A lightning bolt icon will appear next to ArticleEdit to indicate that it is now the Startup Form

The App Browser with ArticleEdit set to Startup Form

Now run the app by clicking the green Run button at the top of the Anvil Editor.

Mouse hovering over the Run button

You should see the ArticleEdit Form running, and the dropdown should be populated with your homepaarticle categories:

The ArticleEdit Form running, with the categories dropdown open, showing that it is populated with the categories from the Data Table.

Remember to set Homepage back as the Startup Form when you’ve finished.

The App Browser with Homepage set to Startup Form

We’ve written the first piece of client-side Python code for our app. We’ve populated the DropDown on our ArticleEdit Form with categories from the Categories Data Table.

In Chapter 4, we’ll enable users to add articles to the database.

Chapter complete

Congratulations, you've completed this chapter!