
I wrote below trigger on opportuntiy to update account field for some reasons it is not workng please suggest me what is the issue in below trigger
ThanksSudhirtrigger update_account_billing_email on Opportunity (before insert, before update) {
for(Opportunity opp:System.Trigger.new)
{
Opportunity op = [SELECT Billing_ContactEmail__c,AccountId from Opportunity
where id in :Trigger.newMap.keySet()];
Account ac = [SELECT Billing_Email__c from Account where id = :op.AccountId];
If ( ac.Billing_Email__c == '')
{
ac.Billing_Email__c = op.Billing_ContactEmail__c;
update ac;
}
}
}

The trigger is firing, but you have to understand trigger context first. Trigger.newMap (and Ids of records) are not available on a before insert operation. See the following link for more info on that: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htmFurther more, your trigger is performing an update or DML inside of a for loop, which will throw an exception in cases where you load several Opportunity records.In other words, your trigger needs a bit of refactoring. I've taken a stab at it for you below: trigger update_account_billing_email on Opportunity (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
for(Opportunity opp:System.Trigger.new){
accountIds.add(opp.AccountId);
}
Map<Id,Account> accountMap = new Map<Id,Account>([Select Billing_Email__c From Account Where Id in :accountIds And (Billing_Email__c = null Or Billing_Email__c = '')]);
Map<Id,Account> accountsToUpdate = new Map<Id,Account>();
for(Opportunity opp : Trigger.new){
Account acct = accountMap.get(opp.AcountId);
if(acct != null){
acct.Billing_Email__c = opp.Billing_ContactEmail__c;
accountsToUpdate.put(acct.Id,acct);
}
}
update accountsToUpdate.values();
}