Serialize and Deserialize Hierarchical Tree Component?

What I’m trying to do:
Serialize and Deserialize Custom Hierarchical Tree Component using simple object as the Data Table backend object.

What I’ve tried and what’s not working:
Serialization:
So far I just have a hard coded python object that gets saved to the backend in the following manner when someone clicks the button to save to the database:

  def button_save_to_database_click(self, **event_args):
    sample tree = {"text" : "Node 1 Text", "checked" : True, "visible" : True, "children" : {"text" : "Node 2 Text" , "checked" : False, 'visible' : False, "children" : None} }
    anvil.server.call('upsert_hierarchy', sample tree)

Deserialization:
This part is the logic that I’ve been working on more. I’ve been able to save and somewhat load the simple object that exists in the database, but the hierarchical structure seems to be lost. Still working on why the parent / child relationships are broken right now.

Code Sample:

  def button_load_from_database_click(self, **event_args):
    tree = anvil.server.call('load_from_database')
    self.node_container.clear()
    cb_root = HierarchicalCheckboxNode()
    cb_root.add_node_from_tree(tree)
    self.node_container.add_component(cb_root)

How a Normal Parent Child Interaction Looks Like:
morefun

How Broken Interaction Looks Like:
“Node 1Text” is supposed to be the parent of “Node 2 text” node. However this relationship is not conserved when building from the database. Also, there should not be a blank top level root node. “Node 1 Text” should be the root, and “Node 2 text” should be its only child node.
morefun

I’m sure it’s something screwy with how I’m doing the recursion. Any help is appreciated as always.

Clone link:
https://anvil.works/build#clone:7CH7XR6GAMNBMWP7=RXZ2I2BPSQQZJBOR45AQANTG

You’ve got a blank node in the form to start with, that’s the one that’s coming out as the blank top level node.

add_node always adds a new instance of HierarchicalCheckboxNode as a child of the current form, whether it’s adding the parent node or the child node.

You should make a distinction in the code between adding the parent node (which should modify the controls you already have in the form) and adding a child node (which should create another instance of HierarchicalCheckboxNode.

1 Like