Hi All,
After having few issues when insert code block did not triggered some field validations - form instance when insertiung sales header and setting document date, and also on sales lines and UOM, I came to the conclusion that it is always better to first insert with Key fields and then update. Am I wrong here? and I'm surprised most of the sample code I have been using did not use this pattern or MS assumes everyone from NAV background and should know this already.
An example of the code:
clear(SalesHeader);
SalesHeader.Init();
SalesHeader.Validate("Document Type", SalesHeader."Document Type"::Invoice);
SalesHeader.Insert(true);
SalesHeader.Validate("Sell-to Customer No.", CustomerNo);
SalesHeader.Validate("Bill-to Customer No.", BillTo);
SalesHeader.Modify(true)
0
Answers
The only thing you are missing is setting the "No." field to blank. When you write a loop and you use the same variable for creating the new document, the Init() command does not clear the primary key fields. Setting the "No." field to blank, and calling Insert(true) will trigger the standard number series to get the next number in your new document.
Here's some of my code from an app that I'm working on, same kind of thing:
RIS Plus, LLC
In BC though, you are never sure, because someone could have changed something or there might be an extension that relies on the existence of the record in the database.
So in simple terms, from BC14 onwards you should always do it the way Daniel suggests so that your code is agnostic to any changes made by other developers.