Salesforce Asked by Steven Hodge on February 21, 2021
Im trying to work out how I can create a parent and child record at the same time. I’ve tried to base it on the example salesforce have provided https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm
I’m using the standard leads object as the parent and have a custom object called Lead_account__c as the child. This is a junction object between the lead and account objects.
There is also an external ID field on the lead object called Azure_Lead_ID.
Lead__c is a look up relationship field on the Lead_account__c object up to the lead object
To me it looks like the example in Salesforce doc, but when running the code I get the following error: Line: 7, Column: 1 Illegal assignment from Lead to Id
Lead_Account__c newleadAcc = new Lead_Account__c(Client__c='0013H000002rmNDQAY');
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields.
Lead newlead = new Lead(Azure_lead_Id__c='SAP111111');
newleadAcc.Lead__c = newlead;
// Create the Account object to insert.
// Same as above but has Name field.
// Used for the insert.
Lead parentLead = new Lead(
LastName='Hallie',
Company= 'Test Company',
Azure_lead_Id__c='SAP111111');
// Create the account and the opportunity.
Database.SaveResult[] results = Database.insert(new SObject[] {
parentLead, newleadAcc });
// Check results.
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Successfully created ID: '
+ results[i].getId());
} else {
System.debug('Error: could not create sobject '
+ 'for array element ' + i + '.');
System.debug(' The error reported was: '
+ results[i].getErrors()[0].getMessage() + 'n');
}
}
You would need to assign the value to the relationship object, not the Id/lookup object. This is __r
rather than __c
:
newleadAcc.Lead__r = newlead;
Correct answer by sfdcfox on February 21, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP