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
DeLiDeLi 

JavaScript Button in Visualforce Page

I have a couple of custom objects related to each other. I created a custom button on the master object which runs an aggregate query:

var gc = new sforce.SObject("Goal_Calculator__c");
gc.Id = '{!Goal_Calculator__c.Id}';
var myQ = "SELECT Goal_Calculator__c, SUM(Jan_Rev__c) FROM Goal_Calculator_Account__c WHERE Goal_Calculator__c = '" + '{!Goal_Calculator__c.Id}' + "' AND Business_Type__c = 'Existing' GROUP BY Goal_Calculator__c";
var myresult = sforce.connection.query(myQ);
gc.Jan_Exist_Bus__c = myresult.records.expr0;
sforce.connection.update([gc]);
window.location.reload();

I than created a visualforce page for the master object (Goal Calculator).
My question is how can I expose/use my custom button on this visualforce page, or how do I implement the same functionality in the visualforce page?

Thank you
 
Suneel#8Suneel#8
You can create a button in your VF page as below

<apex:commandButton value="Calculate Jan Rev Sum" action="{!calculateSum}" reRender="myForm" />

Assuming gc is the record of Goal Calculator currently in contect and goalCalculatorId is the id of the record,code in the controller would go like this.
public PagerReference calculateSum(){
	AggregateResult ar=[SELECT Goal_Calculator__c, SUM(Jan_Rev__c) janRevSum FROM Goal_Calculator_Account__c WHERE Goal_Calculator__c = :goalCalculatorId AND Business_Type__c = 'Existing' group by Goal_Calculator__c];
	gc.Jan_Exist_Bus__c=Integer.ValueOf(ar.get('janRevSum'));
	return null;
}

If there is master detail relationship between these two objects and you want the sum to be updated directly you can make us of Roll Up Summary field feature and it is very much effective compared to this approach
DeLiDeLi
I did solve the problem by writing the javascript function in the VF page and calling it on button click.
Yes I could have used the Roll Up formula field, if I didn't have over 20 fields to calculate. I'm obviously not creating 20+ buttons :)
Something I couldn't get the page to do was to refresh, after the record update though.

Thanks a bunch for the suggestion, I may actually go the route of the custom controller