What I’m trying to do:
Trying to call a form with parameters, in code add components (forms) and have the parameters available to those add components.
What I’ve tried and what’s not working:
I’ve tried calling the form with the parameters, however, I have to add my forms in the form_show event, and I cannot figure out how to make those parameters available in the form_show event
Code Sample:
rom ._anvil_designer import main_formTemplate
from anvil import *
import anvil.server
from ..panel1 import panel1
from ..panel2 import panel2
from ..panel3 import panel3
class main_form(main_formTemplate):
def __init__(self, data, metrics, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
print(data)
print(metrics)
def form_show(self, **properties):
self.main_cp.add_component(panel1())
self.main_cp.add_component(panel2())
self.main_cp.add_component(panel3())
f = Component()
Clone link:
https://anvil.works/build#clone:X4LE4AJ56G4AB6VW=A44MRCPK2FZY4ENXTGKKYPAP
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