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
ChinnuChinnu 

Trigger to create opportunity name in default format

How to write. ATrigger to create opportunity name in default format ( e.g before opportunity is interested the name of the opportunity should be Account name+created user+dateandtime

Thanks in advance 
Harsh P.Harsh P.
Hi chinu,

Try the below simple trigger :
trigger DefaultoppNameTrigger on Opportunity (before insert,before update) {
    
    for(Opportunity o : Trigger.new){
        for(account a : [select Id,Name from account]){
            if(o.AccountId == a.Id){
            o.Name =a.Name +' '+ userinfo.getName() +' '+ system.now();
                }
            }
    }
}

Thanks & regards,
Harsh P.
Ajay K DubediAjay K Dubedi
Hi Chinnu,
Try the following code:
Trigger:
trigger triggerName on Opportunity (before insert) {
    if (Trigger.isBefore && Trigger.isInsert) {
   ClassName.methodName(Trigger.new);
  } 
}

Class:
class ClassName{
 public static void methodName(List<Opportunity> opplist){
  Set<Id> AccountIdSet = new Set<Id>();
  Set<Id> UserIdSet = new Set<Id>();
  List<Datetime> dt = new List<Datetime>();
  
  for(Opportunity o : opplist){
   AccountIdSet.add(o.AccountId);
   UserIdSet.add(o.CreatedById);
   dt.add(o.CreatedDate);
  }
  List<Account> AccountNames = [SELECT Name FROM Account WHERE Id IN: AccountIdSet];
  List<User> UserName  = [SELECT Name FROM User WHERE Id IN: UserIdSet];
  for(Opportunity o : opplist){
   for(Account a : AccountNames){
    for(User u : UserName){
     for(Datetime d : dt){
      o.Name = a.Name + u.Name + d;
      break;
     }
     break;
    }
    break;
   }
  }
 }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi 
ChinnuChinnu
Thank you Ajay & harsha!
both worked!