Sorry, but almost all assumptions in this code are wrong.
And I tell you why:
You added this code in the “OnValidate” trigger of the “DecimalField”.
This code is being executed when anybody writes a value into the field. This will not happen, s your code is not getting executed.
You tried to divide the total costs of all item ledger entries (= total of all purchases and all sales and all positive and negative adjustments ever done) by the Invoiced Quantity of the first record.
You tried to do a calcums on a flowfield. A flowfield does not exist in the database, therefore it cannot be “Summed” up by a calcsums command.
If you want to have the “Cost per Unit” written into the DecimalField, you should:
Add some new Local Procedure to a codeunit, call the properties of those procedure and make them Event Subscribers.
Point to Table 32, OnBeforeInsert
Point to Table 32, OnBeforeModify
Point ot Table 5802, OnBeforeInsert
The first two should caluclate the value directly:
IF Rec.“Invoiced Quantity” <> 0 THEN BEGIN
Rec.CALCFIELDS(“Cost Amount (Actual)”);
Rec.DecimalField := Rec.“Cost Amount (Actual)” / Rec.“Invoiced Quantity”; // You could also want to call a ROUND to get a better value
The third one must get the right Item Ledger Entry, (based on the “Item Ledger Entry No.” of the Value Entry and call the same code as above with the ILE, then don’t forget to MODIFY the ILE.
Why do I suggest this way:
Whenever a new Value Entry is being written to the database (an item ledger entry is revalued), the Cost per Unit changes. Therefore you would have to recalculate the value every time a new Value Entry is created.