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
Basil RobertsonBasil Robertson 

Apex trigger to pull name field from custom object linked to Opp via lookup relationship

Hi Everyone,

I have custom object, lets say contract (API name contract2__c), which is linked to opportuinities via a lookup relationship. I would like a field update on a field on the opportunity "contract_name__c" with the name of the contract which is linked to the opportunity.

This is the code I have so far:
 

trigger PullContactName on Opportunity (before insert, before update) {
     set<ID>cObjectID = new set<ID>();
    
    for (Opportunity opp : Trigger.new){
        if(opp.contract2__c != null){
            cObjectID.add(opp.contract2__c);
        }
    }
    
    if(!cObjectID.isEmpty()){
        
        Map<ID,contract2__c> cObjectMap = new Map<ID,contract2__c>([select Id,Name from contract2__c where Id IN: cObjectID])
;

        for(Opportunity opp : trigger.new){
            if(cObjectMap.get(opp.contract2__c).Name != null){
                opp.Contract_Name__c = cObjectMap.get(opp.contract2__c).Name;
            }
        }
        
    }
}

But it keeps throwing a problem stating on line 6 that "Invalid field contract2__c for SObject Opportunity"
Please help

kind regards,
Basil Robertson
Sumit Kumar Singh 9Sumit Kumar Singh 9
Hello Basil,

1)   Check the API name of the custom Field on Opportunity. Please make sure that it is "contract2__c" or not?
2)  If API name is correct, Please chech the Fiels Level Security for this Field. Please, Make sure that field is visible to the User profile.

Let me know if it helps you.


Thanks,
Sumit Kumar Singh
LakshmanLakshman
You need to check the API name of the Lookup relationship -  contract2__c ) on Opportunity, field level security wont matter here.  Check if it is a managed package field, add namespace if it is.