function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kenji775Kenji775 

Create Records With Master-Detail Relationship

Hello All,

This feels like kind of a stupid question, but it is driving me nuts. I am using Apex to create a record when another event happens. The record I am creating has a master-detail relationship with campaigns. However, when I try to specify the Campaign, it throws the error.

 
Save error: Field is not writeable: Payments__c.Master_Study__c    Sandbox/src/classes    ProcessCancelRecords.cls    line 27    1247502651652    1952 

 

Below is my code, the line

 Payment.Master_Study__c= r.Master_Campaign__c;

is the one causing the problem. Thats the master detail field I want to populate. I know you cannot modify that field after creation, but these records don't even exist yet, so I don't know why it is freaking out.

 

 

public class ProcessCancelRecords { public static void ProcessCancels (Respondent__c[] respondents) { DateTime dT = System.now(); Date myDate = date.newinstance(dT.year(), dT.month(), dT.day()); list<Payments__c> PaymentsToCreate = new List <Payments__c>(); for (Respondent__c r : respondents) { if(r.Respondent_Status__c == 'Cancelled') { Payments__c Payment = new Payments__c(); Payment.Contact__c = r.Respondent__c; Payment.Contribution_Amount__c = 0.00; Payment.Payment_Amount__c = 0.00; Payment.RespondentRecord__c = r.Id; Payment.Status__c = 'Cancelled'; Payment.Study__c = r.Child_Campaign__c; Payment.Host__c = 'Auto Create From Rule'; Payment.Notes__c = 'This was automatically Created when this respondent cancelled'; Payment.Payment_Received_Date__c = myDate; //Apperantly you cannot specify the master detail relationship field even //though this is a new record. I know you cannot modify the master detail after //the fact, but you cannot even specify it before creation. Weird. //Payment.Master_Study__c= r.Master_Campaign__c; PaymentsToCreate.add(Payment); } } insert PaymentsToCreate; } }

 

 

 

Sara-CASASara-CASA

Hey Kenji, did you figure this out?  I'm working on a similar problem...

Thanks,

Sara

Kenji775Kenji775

I think I might have. Let me check my code and post back.

Kenji775Kenji775

I have no idea if this might work, but you might be able to use the approach of how you set an ID when you create an object.

 

Campaign umbrellaCampaign = new Campaign(Id=String.valueOf(MasterCampaign.get('parentId')));

 

will let you set the ID. So maybe you could change Id= to your relationship field? I don't know. worth a shot.