+ Start a Discussion
SF DakshendraSF Dakshendra 

How to assign opportunity record types based on account record types using apex trigger and not for converting lead just account and opportunity?

Hi 
How to assign opportunity record types based on  account record types using apex trigger and not for converting lead just using account and opportunity record types?

Thanks
Dakshendra.R
Best Answer chosen by SF Dakshendra
suresh sanneboina 4suresh sanneboina 4
Hi,

Please try the below code. the account and opportunity should have same record type.
trigger Opportunityupdater on Opportunity (before insert) {
    if(Trigger.isBefore) {
		Set<Id> accountId=new Set<Id>();
		for(Opportunity opp : Trigger.new) {
		  if(opp.AccountId !=null)
		  {
			accountId.add(opp.AccountId);
		  }
		}
		
		if(!accountId.isEmpty())
		{
			Map<Id,Account> mapAccount=new Map<Id,Account>([Select Id,Recordtype.Name from Account where Id IN :accountId]);
			if(!mapAccount.isEmpty())
			{
				for(Opportunity opp : Trigger.new) {
					if(opp.AccountId !=null && mapAccount.containsKey(opp.AccountId))
					{
						opp.recordTypeId =Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(mapAccount.get(opp.AccountId).Recordtype.Name).getRecordTypeId();
					}
				}
			}
		}
    }
}