You need to sign in to do that
Don't have an account?
EvdHurk
How to update Opportunity owner to account owner before insert
Hi,
I am starting with a Apex trigger and want to update the Opportunity owner to Account owner before insert.
Does anybody has a code to get me starting?
Tnx in advance
This will work I think. Its bulkified too.
trigger OpportunityTrigger on Account (before insert)
{
List<String> accountIds = new List<String>();
List<Account> parentAccounts = new List<Account>();
for(Opportuinty oppty : Trigger.new)
{
accountIds.add(oppty.AccountId);
}
parentAccounts = [Select Id, OwnerId from Account where Id in :accountIds];
Map<String,Account> accountMap = new Map<String,Account>();
for(Account a : parentAccounts)
{
accountMap.put(a.Id,a);
}
for(Opportunity oppty : Trigger.new)
{
Account parentAccount = accountMap.get(oppty.AccountId);
if(parentAccount != null)
{
oppty.OwnerId = parentAccount.OwnerId;
}
}
}
Below is the Sample code -
Opportunity opp = [Select id, OwnerId from Opportunity];
Account acc = new Account(OwnerId = opp.OwnerId, name = 'AccName');
insert acc;
This code actually works now tnx, i adapted 2 things ;)
Is het possible to trigger the code by a checkbox on opportunity? So if this checkbox is true the trigger works and if is false just uses the create owner of the opportunity? Or maybe that a certain profile only can trigger this code?
trigger OpportunityTrigger on Opportunity (before insert){
List<String> accountIds = new List<String>();
List<Account> parentAccounts = new List<Account>();
for(Opportunity oppty : Trigger.new)
{
accountIds.add(oppty.AccountId);
}
parentAccounts = [Select Id, OwnerId from Account where Id in :accountIds];
Map<String,Account> accountMap = new Map<String,Account>();
for(Account a : parentAccounts)
{
accountMap.put(a.Id,a);
}
for(Opportunity oppty : Trigger.new)
{
Account parentAccount = accountMap.get(oppty.AccountId);
if(parentAccount != null)
{
oppty.OwnerId = parentAccount.OwnerId;
}
}
}