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
mng0827mng0827 

insert new opportunity trigger

Hi,

I'm trying to create a simple trigger which creates an opportunity whenever an account field is updated. However, I'm getting this error upon saving:

Error: Compile Error: Loop variable must be of type SOBJECT:Opportunity at line 3 column 19

Here's my trigger:

trigger CreateNewOppinPeakfolio on Account (after insert, after update){
     List <Opportunity> insertopp = new List <Opportunity> ();    
     for (Account acc: Trigger.new){
        if(acc.Analysis_Status_in_Peakfolio__c == 'Portfolio Analysis'){
            Opportunity o = new Opportunity ();
            o.Name = acc.Name;
            o.StageName = 'Portfolio Analysis';
            o.CloseDate = system.today() + 30;
            o.AccountId = acc.Id;
            insertopp.add(o);
        }
    }
    try {
            insert insertopp;
    }
    catch (system.Dmlexception e) {
            Trigger.new[0].addError(e);
    }
}
magdielhfmagdielhf
I just tried your code without the try/catch block and it worked, I got the opportunity created,

My suggestion will be, instead of adding the whole exception to the trigger, get the message and add just the exception message string, this might be the cause, not sure about adding a DML exception from a different SObject,

This is what I did:
Using Eclipse, I opened my project and created a new trigger named CreateNewOppinPeakfolio to execute on after insert and after update for Account,
Added your code and removed the lines handling the exception,
Save it back and created an Account for testing this trigger
Got the account created and the opportunity related to it

trigger CreateNewOppinPeakfolio on Account (after insert, after update) {
	
     List <Opportunity> insertopp = new List <Opportunity> ();    
     for (Account acc: Trigger.new){
        if(acc.Analysis_Status_in_Peakfolio__c == 'Portfolio Analysis'){
            Opportunity o = new Opportunity ();
            o.Name = acc.Name;
            o.StageName = 'Portfolio Analysis';
            o.CloseDate = system.today() + 30;
            o.AccountId = acc.Id;
            insertopp.add(o);
        }
    }    

    //try {
            insert insertopp;
    //}
    //catch (system.Dmlexception e) {
            //Trigger.new[0].addError(e);
    //}
    
}