I was wondering about the best pattern for updating the database with only the fields of a form that have changed. I understand that this works neatly with the write-back function, but how is it done best if I prefer a server function to handle database operations?
Let’s say I have a form with four fields to create and display a record. Two of the fields are filled at creation of the record. One is filled by another user that can only fill this one field and the last is filled by the creator at a later point in time.
This could be done with three different functions, each of which only update the fields that are filled out. Though it doesn’t feel it’s supposed to be that way.
I can imagine that somehow a unified function can be created, that checks for updates first and then writes the the unchanged old and updated new entries to the database. But that feels counter intuitive as well.
So is there a preferred pattern or something that makes sense, at least if your Dutch?
I think this is very much a matter of taste, but here’s an example of using a universal ‘create or update’ function as you describe:
@anvil.server.callable
def create_or_update_record(record=None, **data):
if record is None:
app_tables.records.add_row(**data)
else:
record.update(**data)
Then, for the inputs you want to be able to modify only one field, do something like:
def text_box_colour_pressed_enter(self, **event_args):
"""This method is called when the user presses Enter in this text box"""
anvil.server.call(
'create_or_update_record',
record=self.item,
favourite_colour=self.text_box_colour.text,
)
The creation function could be:
def button_create_click(self, **event_args):
"""This method is called when the button is clicked"""
anvil.server.call(
'create_or_update_record',
name=self.text_box_name.text,
age=int(self.text_box_age.text),
)
Here’s an app that uses functions like that to modify a record in Data Tables with a form that creates records, and Data Grid cells that edit one of two fields:
Something else to mention, based on what you posted:
Two of the fields are filled at creation of the record. One is filled by another user that can only fill this one field and the last is filled by the creator at a later point in time.
It sounds like you need trusted business logic to ensure that only certain users can update certain fields at certain times (possibly in a certain sequence). In that case, you’re going to need to check the identity of the logged in user, state of the row, etc, - so, having a separate server function for each step might make sense.