Capturing Form component attributes into a data structure

There is no respective dict for each checkbox.

The form represents a document (or object or part or whatever).

self.item in the form is a dictionary describing that document.

Each component represents one (or more) property of the document.

For example, if self.item represents a truck:

# example of self.items
{
    'truck_number': '123',
    'is_closed': True,
    'has_shipped': False,
}

# examples of databindings
# databinding for the textbox self.truck_number
text    -> self.item['truck_number']

# databinding for the checkbox self.truck_is_closed
checked -> self.item['is_closed']

# databinding for the checkbox self.truck_has_shipped
visible -> self.item['is_closed']
checked -> self.item['has_shipped']

Or, if you use the object self.truck instead of the dictionary self.item:

# example of object self.truck
self.truck.number = '123'
self.truck.is_closed = True
self.truck.has_shipped = False

# examples of databindings
# databinding for the textbox self.truck_number
text    -> self.truck.truck_number

# databinding for the checkbox self.truck_is_closed
checked -> self.truck.is_closed

# databinding for the checkbox self.truck_has_shipped
visible -> self.truck.is_closed
checked -> self.truck.has_shipped

Then in your code you will have:

if self.truck_is_closed.checked:
    # manage closed truck
else:
    # manage open truck

But, since databinding can be bi-directional, you don’t even need to deal with the components. You can simply do:

if self.item['is_closed']:
    # manage closed truck
else:
    # manage open truck

# or:
if self.truck.is_closed:
    # manage closed truck
else:
    # manage open truck

I usually work with my own classes, not with dictionaries, so all I need to do is:

self.truck.update()

and, since the databinding is bi-directional and the properties have been updated, then the object attributes have been updated, so its update() method can do its job relying on fresh data.

This makes it easy to let the form do the form and my class manage the logic. The form defines the databinding between the input components and the attributes of my object, then calls one method to tell the object to process its new status, and the object does its job. This makes it very easy to test the business logic independently from the UI.

1 Like