You question shows that you have understood most of it, but take a look at how its done in example sales invoices and when you post sales invoices. Now even if your setup is not as complex, then you should always try to create the same concept as used by Microsoft. So I suggest that you create your code in a codeunit and calls the codeunit from the form. Otherwise it’s difficult to see from your question what you’re are actually trying to do, and what you need to know.