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
sumit dsumit d 

trigger to validate opportunity name

Hi All,
 i want to Develop a trigger to validate that Opportunity Name should starts with this Format - AccountName :  ,
error message should be "Invalid name, Please start name with Account's Name: " - i want to Use custom label for message.
 i want that whenever new Oppportunity will be created than the naming of Opportunity should be like this - Exp:- Account name is ABC than the Opportunity name should be - ABC : 1234 OR
ABC : XYZ

if its not in this format than error message will be shown.
Any suggestions how to Achieve this?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sumit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger OppNameBasedOnAcc on Opportunity (after insert) {
    
    List<Id> oppIds = new List<Id>();
    for (Opportunity opp:Trigger.new ){
        oppIds.add(opp.Id);
    }
    
    List<opportunity> op = new List<Opportunity>();
    
    for(Opportunity opps : [SELECT Id, Name, Account.Name FROM Opportunity WHERE Id IN :oppIds]){
        if(opps.Name == opps.Account.Name + ' '+':' +' '+'1234'){
            op.add(opps);
        }
        else{
            Map<id,Opportunity> Mapjun = Trigger.newmap;
            Mapjun.get(opps.id).Name.adderror('Opportunity name should start with Accounts Name');
        }
    }       
    
    if(op.size()>0){
    	UPDATE op;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Mohan Chaitanya PalaparthiMohan Chaitanya Palaparthi
Hi Khan Anas
      i have tried your code,and i have created an opportunity with name : mohan :123
                                                                                                       account name : 123
i have an account name amazon so i gave amazon: 123
for all above cases i got error message