+ Start a Discussion
mw6mw6 

update lookup field on custom object using trigger

I have the below trigger

I am using another trigger to create a person account when a new student is created.  After this when the student enroll to a course, a new class allocation is created in 'Class_Allocation__c object.  Once this record is created, I want to copy the contact.id into a lookup field 'Related_Contact__c' on Class_Allocation__C, not sure what is wrong with the trigger.

From Student__C  when a person account is created, I am storing ID (Salesforce) and Student ID into Contact fields Salesforce_Id_from_Student_Object__c, Student_Id_from_Student_Prospects__c fields.  I am using the Student_Name__C field from class_allocation__c to match from Contact 'Student_Id_from_Student_Prospects__c'

No error, and the 'Related_Contact__C on Class_Allocation__c (look up) is not getting populated.  Can anybody help on this

trigger Updatecontactidonclassallocation on Class_Allocation__c (after insert) {
    Set<Id> AllocIds = new Set<Id>();
    for (Class_Allocation__c dReg : Trigger.new)
        AllocIds.add(dReg.Student_Name__C);
     map<id, contact> userContact =
                new map<id, contact>([SELECT Id,Student_Id_from_Student_Prospects__c,Salesforce_Id_from_Student_Object__c FROM contact
                                   WHERE Student_Id_from_Student_Prospects__c IN:AllocIds]);
    for(Class_Allocation__c o: trigger.new){
        if(o.Related_Contact__C == '') {
            o.Related_Contact__C = userContact.get(o.ID).Id;
        }
    }
}


 
Alain CabonAlain Cabon
Hi,

after insert : Can change fields using trigger.newNot allowed. A runtime error (not during the compilation) is thrown, as trigger.new is already saved. Fortunately,  if(o.Related_Contact__C == '') is always false (null value).

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables_considerations.htm

before insert: Can change fields using trigger.new = Allowed

trigger Updatecontactidonclassallocation on Class_Allocation__c (before insert) {
   ...
    for(Class_Allocation__c o: trigger.new){
        if (String.isEmpty(o.Related_Contact__C)) {
            o.Related_Contact__C = userContact.get(o.ID).Id; 
        }
    }
 }

Regards