I am working on creating different forms based on whether a user is logged in or not. I was wondering if Anvil has the capability to create persistent navbars i.e. a navbar that can be created in one spot then used on each form?
Yes, you can do that in a number of different ways. One of them is to create a main form that has your navbar and then only change the contents of the main column-panel as you navigate to other forms.
If you can’t be bothered to change your app to use navigation you can do what I’m doing in my current app, which is to create an instance of your navbar and hold the reference to it when the app first loads in a startup module. As you change the form you can then grab the instance and add to your new form as you want. You just need to be aware that a component can only in one place at a time and even when your form is not loaded, the component holds the reference to it’s parent, so you need to first remove the navbar from the previous parent before adding again.
Here’s an exemple:
On your StartupModule you would have
NAVBAR = None
def getNavBar():
global NAVBAR
if NAVBAR is None:
NAVBAR = NavBar() # First time: creates the instance
return NAVBAR
Then, in each form you need to use the navbar you:
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.
nav_bar = StartupModule.getNavBar()
if nav_bar.parent is not None:
#This navbar is used in another place: remove it from there BEFORE anything
nav_bar.remove_from_parent()
self.content_panel.add_component(nav_bar)
Yeah… It’s not as easy as it sounds. There’s probably easier ways to do that while not changing the app to a single page format, but this is something in the line of what I’m doing.
I would just create a nav bar form (from a blank form), designing it with all the buttons to call open_form() and navigate your app, then turn it into a custom component that you can drag on to any page you want.
You could even add custom properties that could tell this component where its being shown, or just pass __name__ to it through code, and add it using .add_component() through code as well.
Third suggestion: you can make one navbar with all the buttons and play with the visible property of each button to hide the options that are not allowed. Something like:
def show_admin_buttons(self):
for button in [self.button_1, self.button_2, self.button_3]:
button.visible = True
def show_less_cool_user_buttons(self):
for button in [self.button_2]:
button.visible = True
for button in [self.button_1, self.button_3]:
button.visible = False