Skip to main content

Notifications

Small and medium business | Business Central, N...
Answered

Custom Api - Deep Insert

Posted on by 35
I am developing a custom apipage  which follows a header / lines pattern as such following the example I am able to create a PART page on the header api so I can make a deep insert. This works as expected.
 
Question: I want to verify on the validation code that the sum of the line quantities equal the totalquantity value in the header - how can i access the lineitems from the header record so i can verify that TotalQuantity equals the sum of the lines?  Is there a way to directy access the post jsonbody from the page triggers of the header?
 
Thanks so much!
 
Example
{
No: 1,
Name: order 1,
TotalQuantity: 12
[
{LineNumber:1, Qty: 5},
{LineNumber:2, Qty: 7}
}
  • Verified answer
    MH-06060002-0 Profile Picture
    MH-06060002-0 35 on at
    Custom Api - Deep Insert
    Thanks to everyone for their input: This is the way I was able to solve the problem while maintaining the built in design pattern, I wanted to share this as deep inserts are barely covered in the the built in documentation:
     
    The following Post Body
    {
        "no": 1907,
        "txtfield1": "header1",
        "testLines":[
            {"txtfield1":"Line1"},
            {"txtfield1":"Line2"}
            ]
    }
     
    Theis is the api page trigger sequence when inserting a header with 2 lines in a single post (deep insert)
    1    Header OnInit    
    2    Header OnOpenPage    
    3    Header OnNewRecord    
    4    Header OnValidate Field    (Could be multiple)
    5    Header OnInsertRecord    header1
    6    Line OnInit    
    7    Line OnNewRecord    
    8    Line OnValidate Field    (Could be multiple)
    9    Line OnInsertRecord    Line1
    10    Line OnNewRecord    
    11    Line OnValidate Field    (Could be multiple)
    12    Line OnInsertRecord    Line2
    13    Header OnAfterGetRecord    
    14    Header OnAfterGetCurrRecord    
     
    The key here is that the Header OnAfterRecord is run again at the bottom of the sequence and is used to send back the json reply to the post. As a result the secret to running code after the completion of the deep insert is as follows
     
    1) In Trigger 3 set  a page variable deepinsertinprocess to true (this is needed as the onaftergetrecord is also run during a get call and we only want certain behavior in the get call if it as a result of the post insert call)
    2) In Trigger 13 Header OnAfterGetRecord test if deepinsertinprocess is true and then conduct code - for example check if there are more than 2 lines.  At this point you can access the sublines as records that match the current Rec.  See below.  Since we are still in the current transaction scope the error we are raising will rollback the original insert!  This can also be used to run code after the completion of the entire post Header and Lines!
     
     trigger OnAfterGetRecord()
        var
            a: Record testapiLines;
            b: Record testapiHeader;
        begin
            if deepinsertinprocess then begin
                a.SetRange(a.HeaderLink, rec.SystemId);
                if a.FindSet() then begin
                    if a.Count <> 2 then
                        Error('Fail On line item count check');
                end;
            end;
        end;
     
  • Suggested answer
    YUN ZHU Profile Picture
    YUN ZHU 71,656 Super User 2024 Season 2 on at
    Custom Api - Deep Insert
    Hi, hope the following can give you some hints as well.
    Tips & Tricks for Creating Custom APIs
     
    Thanks.
    ZHU
  • gdrenteria Profile Picture
    gdrenteria 11,042 Most Valuable Professional on at
  • MH-06060002-0 Profile Picture
    MH-06060002-0 35 on at
    Custom Api - Deep Insert
    Thanks so much for your reply - The issue is accessing the requestbody while utilizing the bultin in custom api design pattern. 
     
    Alternatively is the only way to do it to rewrite the API Part and parse the nested json manually for the line items?
     
    Thanks
  • Suggested answer
    Nyakinyua Profile Picture
    Nyakinyua 52 on at
    Custom Api - Deep Insert
    This is the approach I'd take
     
    [EventSubscriber(ObjectType::Table, Database::<Table Name>, 'OnBeforeInsertEvent', '', <SkipOnMissingLicense>, <SkipOnMissingPermission>)]
        local procedure OnBeforeInsert(var Rec: Record "YourHeaderTable"; var xRec: Record "YourHeaderTable"; RunTrigger: Boolean)
        var
            JsonObject: JsonObject;
            LineItemsArray: JsonArray;
            LineItem: JsonObject;
            TotalQuantity: Integer;
            SumQty: Integer;
        begin
            // Parse the JSON body from the API request
            JsonObject := JsonObject.Parse(Rec.RequestBody);
     
            // Extract TotalQuantity from the header
            TotalQuantity := JsonObject.GetValue('TotalQuantity');
     
            // Extract LineItems array
            LineItemsArray := JsonObject.GetArray('LineItems');
            SumQty := 0;
     
            // Loop through LineItems and sum quantities
            foreach LineItem in LineItemsArray do begin
                SumQty += LineItem.GetValue('Qty');
            end;
     
            // Validate that the sum of quantities matches the TotalQuantity
            if SumQty <> TotalQuantity then
                Error('The sum of line quantities (%1) must equal the TotalQuantity (%2).', SumQty, TotalQuantity);
        end;

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Complete!

🔔 Be sure to subscribe to the new forums you are interested in to stay up to date! 🔔

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,902 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 229,297 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans