How to pass parameters from to a form_show()

The simplest way would be to make them form properties:

class main_form(main_formTemplate):
  def __init__(self, data, metrics, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.data = data
    self.metrics = metrics
    print(data)
    print(metrics)

That makes those available to all your component event functions since event functions are instance methods.

Alternatively, if you for some reason don’t want to make them properties, you can pass them as arguments like this:

from ._anvil_designer import Form1Template
from anvil import *
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
import functools

class Form1(Form1Template):

  def __init__(self, data, metrics, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    print(data, metrics)
    self.add_event_handler('show', functools.partial(self.form_show, data=data, metrics=metrics))
  
  def form_show(self, data, metrics, **event_args):
    print(event_args)
    print(data)
    print(metrics)
    # Any code you write here will run when the form opens.

Though, that wouldn’t keep those values up to date if they change outside the function (not usually an issue for an event like form_show, but would be for many other events).

Also, this is an escape hatch that removes the benefit of the Anvil Editor’s auto event handler registration.

2 Likes