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
anyioneta1.3025054394678596E12anyioneta1.3025054394678596E12 

trigger Relationship Field

List<Course_Allocation__c> allocateList = new List<Course_Allocation__c>() ;

for(Lecturer__c lec: Trigger.new){                        
                myList.add(new Course_Allocation__c(Name = lec.Name, Full_Name__c = lec.Last_Name__c,
                Email__c = lec.Email__c, Mobile_Number__c = lec.Mobile_Number__c,
                Department__c = lec.Department__r.Name));
 }


But after insertion Department__c field is empty, why?


JohanLiljegrenJohanLiljegren
When the trigger fires you get access to e.g. Trigger.new, which you're using here. Problem is, Trigger.new only gives you access to (a list of) Lecturer__c records, not their related records. In this case, this means you have access to the ID of the related Departmeny__c record, but not the data in that record. So when you're attempting to traverse the relationship (lec.Department__r) all you get back is null.

You will need to gather all the Department__c IDs in a list and then perform a SOQL query, querying for the data you need from these records, i.e. the Name values.

I hope this helps.
anyioneta1.3025054394678596E12anyioneta1.3025054394678596E12

Yp it helped, But Pls could u scramble how the code could look like?

JohanLiljegrenJohanLiljegren
This code pattern exist all over the place in tutorials. Start by reading the Apex Developer Guide and you'll figure it out.
Rahul SharmaRahul Sharma

I agree with Johan, For lookup field you just have to give id of lookup record, not the lookup name.

Try this:

List<Course_Allocation__c> allocateList = new List<Course_Allocation__c>() ;

for(Lecturer__c lec: Trigger.new){                        
                myList.add(new Course_Allocation__c(Name = lec.Name, Full_Name__c = lec.Last_Name__c,
                Email__c = lec.Email__c, Mobile_Number__c = lec.Mobile_Number__c,
                Department__c = lec.Department__c));
 }

 Hope it helps.

anyioneta1.3025054394678596E12anyioneta1.3025054394678596E12

 Compile Error:

Invalid foreign key relationship:

Lecturer__c.Department__c 

 

 

To clearify, Department__c is a Child of Lecturer__c

 

>>>>>What i intend to achieve is

Department__c = Department__r.Name

i.e. Department__c should hold the Nave value which happens to be a forien key in Lecturer__c