Salesforce Asked by Rameshkumar Sakthivel on November 19, 2021
i need to update the opportunity account field for account field null values.
trigger AccountCreationFromOpportunity on Opportunity (before update) {
for(Opportunity o :trigger.old){
if(o.AccountId == Null){
Account acct = new Account();
acct.Name = 'New Account';
acct.Zip_Code__c = '75001';
insert acct;
}
}
// You can try this code
trigger AccountCreationFromOpportunity on Opportunity (before update) {
// Create a Map op Opportunity Id to Account
// It would be trigger.New sicnce you would be updating in Update call. Trigger.old is readonly
Map<Id,Account> mapOppIdToAccount = new Map<Id,Account>();
for(Opportunity o :trigger.New){
if(o.AccountId == NULL){
Account acct = new Account();
acct.Name = 'New Account';
// Add the opp Id as key and new account as values in the map
mapOppIdToAccount.put(o.id,acct);
}
}
// If the new Account List/Map is not empty then Insert accounts
if(!mapOppIdToAccount.IsEmpty()){
Database.Insert(mapOppIdToAccount.Values());
}
// Execute the for loop on trigger.new again
for(Opportunity opp :trigger.New){
if(opp.AccountId == NULL){
//Checking if the New account is present or not
if(!mapOppIdToAccount.IsEmpty() && mapOppIdToAccount.ContainsKey(opp.Id)){
//Update the AccountId field on Opportunity record by fetching account Id from the Map that we inserted
opp.AccountId = mapOppIdToAccount.get(opp.Id).Id;
}
}
}
}
This is the bulkified version of the code
Answered by Narendra Jain on November 19, 2021
trigger OpportunityTrigger on Opportunity(before update){
if(Trigger.isbefore )
{
if(Trigger.isUpdate ) {
List<Opportunity> opps = new List<Opportunity>();
for(Opportunity o : Trigger.new){
if(o.AccountId == NULL){
opps.add(o);
}
}
Account acc = new Account();
acc.Name = 'Test123';
insert acc;
for(Opportunity o : opps){
o.AccountId = acc.Id;
}
}
}
}
It is not recommended to create an Opportunity without an Account basically an Orphan Opportunity. If you want an Orphan Opportunity to get a Parent(account) this code above does that for you.
But the thing is it will create a new Account record every time the opportunity trigger is fired.
You can change that to a already created record of Account object and refer the Account Id in opportunity to the Id of that account record.
Please, try to give as much information with the question to make it understandable in no time. And mark the answer useful if it gives what you need. Cheers :)
Answered by Tushar Saxena on November 19, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP