I am trying to insert Account/Contact/Customer records into SFDC using Rest API. i have written the following class. I am able to create the Accounts and Contacts, but I'm having issues creating Customer records. In my setup, Customer is a child of Contacts, and Contacts a child of Accounts. How should I rewrite my class and JSON to insert Customer records along with Contacts and Accounts in a single call? Here's my apex class:
@RestResource(urlMapping='/test/*')
global with sharing class OrderWebServices{
@HttpPost
global static void createSomething(Wrapper1 test){
Account obj = new Account();
obj.Name = test.name;
obj.AccountNumber = test.accountnumber;
obj.External_Id__c = test.externalid;
insert obj;
List<Contact> conList = new List<Contact>();
for(Wrapper2 con : test.Wrapper2){
Contact obj2 = new Contact();
obj2.LastName = con.lastname;
obj2.Email = con.email;
obj2.AccountId = obj.Id;
conList.add(obj2);
}
insert conList;
//Below doesn't insert related Customer
List<Customer__c> csList = new List<Customer__c>();
for(Wrapper3 cs : test.Wrapper2){
Customer__c obj3 = new Customer__c();
obj3.LastName__c = cs.lastname;
obj3.Email__c = cs.email;
obj3.AccoountId = obj.Id;
csList.add(obj2);
}
insert csList;
}
global with sharing class Wrapper1{
public String name{get;set;}
public String accountnumber{get;set;}
public List<Wrapper2> Wrapper2{get;set;}
}
global with sharing class Wrapper2{
public String lastname{get;set;}
public String email{get;set;}
public List<Wrapper3> Wrapper3{get;set;}//Add this for Customer object?
}
global with sharing class Wrapper3{
public String lastname{get;set;}
public String email{get;set;}
}
}
Here's my JSON:
{
"test": {
"name": "Test Acc",
"accountnumber": "12345",
"externalid": "12345",
"Wrapper2": [{
"lastnmame": "last",
"email": "[email protected]",
"Wrapper3": [{
"lastname": "customer",
"email": "[email protected]"
}]
},
{
"lastnmame": "last2",
"email": "[email protected]",
"Wrapper3": [{
"lastname": "customer2",
"email": "[email protected]"
}]
}]
}
The Account record and Contact records are inserted, but the associated Customer__c records are not inserted. I have an external id field 'External_Id__c' which ties all three records, even though Contact is a child of Accounts, and Customer__c is a child of Contacts.
How can I revise the class to be able to insert multiple contacts and multiple Customer__c records?
Wrapper3
field of theWrapper2
. class. Better to use different naming for classes and fields to avoid confusion, particularly when the field is actually holding an array/list and not a single object. You will have to loop over theWrapper2
objects again to collect yourWrapper3
objects and have the parentWrapper2
Id's available (after theWrapper2
objects have been inserted).