Preserving global variables after loading new form

Hi

If I have a multiuser app, and in one form I do assign datatable to a variable:

  class Main(MainTemplate):

  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.
    
    #Login form
    while not anvil.users.login_with_form():
      pass
    
    self.my_tasks = anvil.server.call('get_tasks') # <-- it calls from a server just like in the mutiuser tutorial 

So now we have it in memory as a part of that form object, when the form loads.

Let’s say I have a button that loads another form, where I also need to use that table.

When I click it loads another form to memory together with another instance of that table as a part of the form2 object.

Is the first form scraped from memory, or does it persist, when I open form 2?

If you open Form2 replacing Form1 with open_form(), then yes, Form1 and all its data is gone.

You can address this problem in two ways:

Keeping the main form alive
You can have one main form with the navigation bar and open the other forms with:

get_open_form().content_panel.clear()
get_open_form().content_panel.add_component(new_panel)

as described here. Then you can do get_open_form().my_tasks from any form you load.

Using a module
Another solution is to create a module and put the global variables in it. Then you can do this from any form:

import Module1

class Form1(Form1Template):
  def __init__(self, **properties):
    self.init_components(**properties)
    print Module1.my_tasks
2 Likes

That solves my issue! Thank you!

I’m glad it helped :slight_smile:

Can you change the post subject to something like “Preserving global variables after loading new form”, so it will help newcomers?

1 Like

Of course I can, and did :slight_smile: