Let’s make the form store the title, content, image and category into our ‘Articles’ table when the user hits ‘Save’.

When the information is first entered, we’ll store it in a Python dictionary. Then if the user hits ‘Cancel’, we can just discard the dictionary - nothing is saved in the Data Table.

We’ll store this dictionary in the item property of the ArticleEdit Form.

All Forms in Anvil have a property called self.item that can be accessed in the Form’s code. We’ll initialise our ArticleEdit Form with an empty dictionary as its self.item.

Edit your add_article_button_click function to look like this:

  def add_article_button_click(self, **event_args):
    # Initialise an empty dictionary to store the user inputs
    new_article = {}
    # Open an alert displaying the 'ArticleEdit' Form
    save_clicked = alert(
      content=ArticleEdit(item=new_article),
      title="Add Article",
      large=True,
      buttons=[("Save", True), ("Cancel", False)],
    )
    # If the alert returned 'True', the save button was clicked.
    if save_clicked:
      print(new_article)

It’s important to remember to change

ArticleEdit() to ArticleEdit(item=new_article)

This means self.item will start as an empty dictionary and we’ll update it as the user fills in the form.

We can update self.item using Data Bindings. You can find Data Bindings in the Properties panel for each component, near the top:

An empty Data Bindings list near the top of the Properties Panel.

Select the ArticleEdit Form. For each of the ‘name’, ‘content’, and ‘category’ inputs, add a Data Binding to self.item:

  • title_box: Bind the text property to self.item['title']
  • content_box: Bind the text property to self.item['content']
  • category_box: Bind the selected_value property to self.item['category']
adding data bindings to the ArticleEdit Form

For the FileLoader component, when the user uploads an image, we want to add it to self.item. To do this, we set an event handler on the FileLoader component which will run when the user uploads an image.

Double click the FileLoader component to create a method for the change event - the change event is raised when a user uploads a file. Its file argument is a Media object containing the chosen file:

adding a 'file_loader_change' event handler to the FileLoader component

Edit the image_uploader_change method to look like this:

  def image_uploader_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader"""
    # Add the image to self.item
    self.item['image'] = file

Now run your app, click on ‘Add new article’, fill in all the fields, upload an image and click the ‘Save’ button.

You should now see your new_article dictionary printed in the Output Panel