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
sakthidharan Ambayiramsakthidharan Ambayiram 

getting the below error when the trigger executes

Error:Apex trigger Test caused an unexpected exception, contact your administrator: Test: execution of AfterUpdate caused by: System.StringException: Invalid id: Dickenson Mobile Generators: Trigger.Test: line 8, column 1
Scenario: whenever the stage field changed to Close won in opportunities , a new object record (Litrack__c)should be created.
Code:
trigger Test on Opportunity (after update) {
    Map<Id,Litrack__c> LitInsert= new Map<Id,Litrack__c>();
    for(Opportunity opNew: Trigger.new){
        for(Opportunity opOld: Trigger.old){
            if(opNew.StageName!=opOld.StageName && opNew.StageName=='Closed Won'){
                Litrack__c Record = new Litrack__c();
                Record.Name=opNew.id;
                Record.Opportunity_Lookup__c=opNew.Name;
                LitInsert.put(Record.id,Record);
            }
        }
      
                insert LitInsert.values();
             
}
}
Best Answer chosen by sakthidharan Ambayiram
SEKAR RAJ.SEKAR RAJ.
Hi Sakthi,

You have to map the Lookup field with the opp.Id and Name with opp.Name.

trigger Test on Opportunity (after update) {
  List<Litrack__c> tobeInsert = new List<Litrack__c>();
    for(Opportunity opNew: Trigger.new){
        for(Opportunity opOld: Trigger.old){
            if(opNew.StageName!=opOld.StageName && opNew.StageName=='Closed Won'){
                Litrack__c Record = new Litrack__c();
                Record.Name=opNew.Name;
                Record.Opportunity_Lookup__c=opNew.Id;

                tobeInsert.add(Record);
            }
        }
      
if(tobeInsert.size()>0){
insert tobeInsert;
}
             
}
}

Thanks,
SEKAR RAJ

All Answers

SEKAR RAJ.SEKAR RAJ.
Hi Sakthi,

You have to map the Lookup field with the opp.Id and Name with opp.Name.

trigger Test on Opportunity (after update) {
  List<Litrack__c> tobeInsert = new List<Litrack__c>();
    for(Opportunity opNew: Trigger.new){
        for(Opportunity opOld: Trigger.old){
            if(opNew.StageName!=opOld.StageName && opNew.StageName=='Closed Won'){
                Litrack__c Record = new Litrack__c();
                Record.Name=opNew.Name;
                Record.Opportunity_Lookup__c=opNew.Id;

                tobeInsert.add(Record);
            }
        }
      
if(tobeInsert.size()>0){
insert tobeInsert;
}
             
}
}

Thanks,
SEKAR RAJ
This was selected as the best answer
Ramesh DRamesh D
@sakthidharan,
try changing below lines, must work
Record.Name=opNew.Name;
Record.Opportunity_Lookup__c=opNew.id;

Thanks
Ramesh
sakthidharan Ambayiramsakthidharan Ambayiram
Thanks Sekar and Ramesh its working now