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
Jaynandan Prasad 8Jaynandan Prasad 8 

trigger to copy the opportunity name in a custom text field in the case object

I need to write a before insert/update trigger to copy the opportunity name(opportunity__c), a lookup field in the case object to another custom text field(CopyOppty__c) in the same object(case).  i wrote the below trigger, but not working.
 
trigger mapOppty on Case (before insert, before update) {
 
    Set<ID> oppIDs = Trigger.newMap.keySet();
    
    Case [] cc = [SELECT Id, Opportunity__c, Opportunity__r.Name FROM Case WHERE Opportunity__c IN :oppIDs ] ;           

    for(case ca : cc)
    {
        ca.copyOppty__c = ca.Opportunity__r.Name ;
    }

    update cc ;
}

 
KaranrajKaranraj
Jaynandan - Do you have any specific reason to write trigger for this scenario? You can achieve this simply by creating a cross object formula field in case object. Check this link to know about corss-object formula field in salesforce https://help.salesforce.com/HTViewHelpDoc?id=fields_creating_cross_object_simple.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=fields_creating_cross_object_simple.htm&language=en_US)

 
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi Jaynandan,

There are some errors in your code 
  1. You cannto get Opportunity Name in case trigger by ca.Opportunity__r.Name because case only keeps the Id of the Opportunity.
  2. You don't need to update the case. Logics of the trigger executes before insert or update i.e. before the system DML operation.
Here I ahave a piece of code which you can try,
 
trigger mapOppty on Case (before insert, before update) {
	Set<Id> OpptyIdSet = new Set<Id>();
	for(case ca : Trigger.New)
		OpptyIdSet.add(ca.Opportunity__c);
	Map<Id, Opportunity> opptyMap = new Map<Id, Opportunity>([SELECT Name FROM Opportunity WHERE Id IN :OpptyIdSet]);
	for(case ca : Trigger.New) {
		if(ca.Opportunity__c != NULL) {
			Opportunity oppty = opptyMap.get(ca.Opportunity__c);
			ca.copyOppty__c = oppty.Name;
		}
	}
}

Thanks :)