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
adi salesforceadi salesforce 

Trigger to update a field in account

There is a custom field total in account. I want to update field value with the sum of previous record total value and new record total record value if they have same industry and record type
Raj VakatiRaj Vakati
try like this
 
trigger AcctTrg on Contact (before Update) 
{
    for(Account a : Trigger.new)
    {
		if( (a.Total__c != trigger.old[a.Id].Total__c )&& (a.Industry == trigger.old[a.Id].Industry ) && (a.RecordTYpeId == trigger.old[a.Id].RecordTYpeId ) ){
           a.Total__c =a.Total__c+trigger.old[a.Id].Total__c ;
		}
      }
}

 
adi salesforceadi salesforce
Hi Raj,
Thank you for giving the solution but I need whenever I insert a record in account with same industry and recordtype like previous account record the total field should be sum of old record total value and new record's fee field value
 
Raj VakatiRaj Vakati
try this
 
trigger AcctTrg on Contact (before insert) 
{
    for(Account a : Trigger.new)
    {
		if( (a.Total__c != trigger.old[a.Id].Total__c )&& (a.Industry == trigger.old[a.Id].Industry ) && (a.RecordTYpeId == trigger.old[a.Id].RecordTYpeId ) ){
           a.Total__c =a.Total__c+trigger.old[a.Id].Total__c ;
		}
      }
}

 
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi adi
trigger AccTrigger on Account(before insert)
{

for(Account acc:Trigger.new)
{
//if there is only single account with same industry and record type
  Account accDup =new Account([Select id,Industry,RecordType from Account where Industry=:acc.Industry and RecordType=: acc.RecordType]);
  acc.total__c=acc.total__c+accList.total__c;
//Multiple accounts with same industry and record type
for(Account accDup:([Select id,Industry,RecordType from Account where Industry=:acc.Industry and RecordType=: acc.RecordType]))
{
  acc.total__c=acc.total__c+accDup.total__c;
}
}
}

To avoid query inside for loop we may use maps instead. 
If this is the exact question you had and need to use maps.Let us know we will let you know a better solution.

Hope this would solve your question!