+ Start a Discussion
jneilan22jneilan22 

Update Opportunity Name

Hello,

 

I am trying to write a trigger that will update the Opportunity Name to a standard format of "Account Name - Record Type of Opportunity (Launch Year in Opportunity)".  My trigger below returns the error "Apex trigger OpportunityName caused an unexpected exception, contact your administrator: OpportunityName: execution of BeforeInsert caused by: System.QueryException: List has more than 1 row for assignment to SObject: Trigger.OpportunityName: line 7, column 1"...I am fairly new to triggers so is there something simple that I am missing?

 

 

 

trigger OpportunityName on Opportunity (before insert) {

    FOR (Opportunity opp: trigger.new) {
 
    Opportunity oppSelect = [
    SELECT RecordType.Name, Name, Launch_Year__c, Account.name, WO__c
    FROM Opportunity];
    
    IF(opp.RecordType.name=='New Business'){
          opp.Name = opp.Account.name+' - '+'New ('+opp.Launch_Year__c+')';
          }
    ELSE IF(opp.WO__c!='Yes' && opp.RecordType.name=='Upsell'){
          opp.Name = opp.Account.name+' - '+'Upsell ('+opp.Launch_Year__c+')';
          }
    ELSE IF(opp.RecordType.name=='Renewal'){
          opp.Name = opp.Account.name+' - '+'Renewal ('+opp.Launch_Year__c+')';
          }
    ELSE IF(opp.WO__c=='Yes' && opp.RecordType.name=='Upsell'){
          opp.Name = opp.Account.name+' - '+'(WO-)';
          }
          
    }

}

Henry AkpalaHenry Akpala

Hi jnellan22,

Just a comment, your trigger will likely result in governor limit exception.

you need to remove the " Opportunity oppSelect = [
    SELECT RecordType.Name, Name, Launch_Year__c, Account.name, WO__c
    FROM Opportunity];" 

from the for loop. 

you can possible run it at the begining of the trigger.

Also, this select statement is going to return a lot of records, might want to add a "Where" clause.  It doesn't seem like you are using for any of the code after that line.

Hope this helps.

-H

jneilan22jneilan22

Thanks.  I removed the SELECT statement so now the error is gone, but the trigger does not update the Opportunity name at all.  Is there something else I am missing?

Henry AkpalaHenry Akpala

Sorry for not getting back to you sooner but have you checked to make sure that there are records that meet the conditions that you are checking for?