You need to sign in to do that
Don't have an account?
SFDC 18
Need to update a field with sum : error
I need to update a field on zone called total sales which display the total sales on agent object in that region
public class TotalSales { public TotalSales(){ for(zone__c z : [SELECT Id,Total_Sales__C FROM Zone__C WHERE Name__c = 'North']){ z.Total_Sales__C = [SELECT Sum() FROM Agent__C WHERE Total_Sales__c ='0' ]; upsert z; } } }
You need to write VF page to run Apex Class. or execute in anonymous window or you can schedule the Apex.
A developer can run the code in anonymous window and if you schedule users cant see the results immediatelly.
In your case i suggest you to write VF page with extension, where user can see the results immediatelly.
Regards,
Bala.
All Answers
You are running soql and also performing DML inside the for loop. That is not a good habit. Can you please post the screenshot of the error you are getting.
Thanks,
Arpit vijayvergiya
you can use sum of a pirticular field. for example Sum(Amount) or Sum(Total_Sales__c). I little understood your requirement. You can mention Count() insted of sum. and importantly when ever you use dml in loop, beware of governer limits.
Ragards,
Bala
2. Never use DML queries and DML updates inside a for loop. Instead, you can use Map for getting Total Sales related to a particular zone and then update List of Zone records. Please refer the link below for salesforce best practices -
'https://developer.salesforce.com/page/Apex_Code_Best_Practices'
3. If "Total_Sales__c" is an Integer value, there is no need to put it in single quote
I'll try this. I have a doubt regarding the execution part. Do we need to execute the code in the anonymous window everytime, like in schedule apex class it upates for every 1 hr. Can you help me out with this.
I'm new to salesforce, currently i work on sap
You need to write VF page to run Apex Class. or execute in anonymous window or you can schedule the Apex.
A developer can run the code in anonymous window and if you schedule users cant see the results immediatelly.
In your case i suggest you to write VF page with extension, where user can see the results immediatelly.
Regards,
Bala.