Here I am keeping the date pickers and text boxes in a list of dictionaries self.travellers
. I add them when I create them, so they are readily reachable later.
I also removed the self.
from variables that are local variables (don’t need to become instance members).
def text_box_travellers_lost_focus(self, **event_args):
trav = int(self.text_box_travellers.text)
self.cp.clear() #clears traveller inputs if the value of trav changes
self.cp2.clear() #clears traveller inputs if the value of trav changes
self.travellers = []
for i in range(trav):
#Creates Boxes for the Traveller Ages
tb = TextBox(type="number",foreground="#000",background="#fff",placeholder=f" traveller {i+1} age")
tb.role = "input"
self.cp.add_component(tb, row=1, col_xs=1, width_xs=1)#this adds the traveller inputs back in
#Creates Boxes for Traveller Details
lb = Label(spacing_above="large", spacing_below="large", foreground="#fff", background="#2b4c80", text=f" Traveller {i+1} Details")
lb.role = "headerlabel"
self.cp2.add_component(lb, row=2, col_xs=2, width_xs=1)#this adds the traveller name boxes
tb2 = TextBox(type="text",foreground="#000",background="#fff",placeholder="Enter Full Name(firstname,lastname)")
tb2.role = "input"
self.cp2.add_component(tb2)#this adds the box where the ages chosen will go
dp = DatePicker(format="YYYY-MM-DD",min_date="1900-01-01",placeholder="Enter as YYYY-MM-DD")
dp.role = "input"
self.cp2.add_component(dp) #this adds the traveller date of birth boxes```
self.travellers.append({'tb': tb, 'tb2': tb2, 'dp': dp}
def button_submit_traveller_details_click(self, **event_args):
for traveller in self.travellers:
row = app_tables.travellers.add_row(TravellerName=traveller['tb2'].text,
TravellerDateofBirth=traveller['dp'].date)
EDIT
I very rarely create components from code.
In a case like this I would very likely create a form with the 4 components, then add the form from code. Yes, the form would be a component created from code, but would be much cleaner.
So the whole form creation loop would be:
def text_box_travellers_lost_focus(self, **event_args):
self.cp.clear()
for i in range(int(self.text_box_travellers.text)):
self.travellers.add_component(TravellerForm(i + 1))
def button_submit_traveller_details_click(self, **event_args):
for traveller_form in self.cp.get_components:
row = app_tables.travellers.add_row(
TravellerName=traveller_form.traveller_name.text,
TravellerDateofBirth=traveller_form.date_picker.date)
This will work if the TravellerForm
has the following signature:
class TravellerForm(TravellerFormTemplate):
def __init__(self, n_traveller, **properties):
and contains components named traveller_name
and date_picker
.