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
Vepsun VarunVepsun Varun 

create trigger to add the opportunity owner into the sales team automatically whenever the opportunity is created ?

SwethaSwetha (Salesforce Developers) 
HI Varun,
You can try below code
trigger AddOppOwnerToSalesTeam on Opportunity (after insert) {

//adds the Opportunity Owner into the sales team automatically whenever the Opportunity is created

List<Opportunity> opps=new List<Opportunity>();

OpportunityTeamMember otm=new OpportunityTeamMember();

List<OpportunityTeamMember> oppTeamMember =new List<OpportunityTeamMember>();

opps=[SELECT Id,OwnerId
FROM Opportunity
WHERE id IN:Trigger.New];

for(Opportunity ops:Trigger.New){
otm.OpportunityId=ops.Id;
otm.UserId=ops.OwnerId;
otm.TeamMemberRole=’Sales Manager’;
// otm.OpportunityAccessLevel=’Read’;
oppTeamMember.add(otm);

}

if(oppTeamMember.size()>0
insert oppTeamMember;
}

}

Reference: https://sfdctechie.wordpress.com/2018/06/14/trigger-scenario/
https://www.infallibletechie.com/2014/05/trigger-to-add-opportunity-owner-in.html

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you​​​​​​​
VijayNiVijayNi
Hi,

Why are we using the below condition 


if(oppTeamMember.size()>0 insert oppTeamMember; }

The trigger .New will acess the newly inserted values right.

Thanks,
Vijay.
SwethaSwetha (Salesforce Developers) 
HI Vijay,
In a scenario when there are no records, it will throw a null pointer exception when you are inserting oppTeamMember during runtime. To avoid this, it is a best practice to check for the size of oppTeamMember and then insert.

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you