If you want to create a record with its child records in Power Pages, there is no way to do it using out of the box forms. But you can do it using JavaScript Power Pages Web API, and with a single Web API call.
In this blog post we will use the example of creating an Account with 2 child Contacts in Power Pages.
Prerequisites
How to setup the request
In your JavaScript code, define a variable or constant with the object you want to submit.
This needs to contain all the fields from the parent object (account) and the array of child objects (contacts) under a property with the relationship name for that parent/child relationship (contact_customer_accounts on this case).
Make sure to get the correct relationship name to use for the child records.
Then use run a POST request to the correct API endpoint for the parent record table, using the webapi.safeAjax method:
let accountWithChildContacts = {
"name": "Test API Call Account",
"contact_customer_accounts": [
{
"firstname": "John",
"lastname": "Doe",
"emailaddress1": "john.doe@contoso.com",
"telephone1": "083-123-4567"
},
{
"firstname": "Michael",
"lastname": "Scott",
"emailaddress1": "michael.scott@contoso.com",
"telephone1": "086-123-4567"
}
]
}
webapi.safeAjax({
type: "POST",
url: "/_api/accounts",
contentType: "application/json",
data: JSON.stringify(accountWithChildContacts),
success: function (res, status, xhr) {
console.log("Saved! - entityID: " + xhr.getResponseHeader("entityid"));
},
error: function (errorResponse) {
console.log("Error");
console.log(errorResponse);
}
});
Results
By running a single WebAPI call as above, the you can parent and child records are created from Power Pages and appear in Dataverse:
The post Create parent and child records with a single WebAPI call in Power Pages appeared first on michelcarlo.
Original Post https://michelcarlo.com/2023/10/25/create-parent-and-child-records-with-a-single-webapi-call-in-power-pages/