1

My VF Page :

<apex:page standardcontroller="Expense__c" extensions="ExpenseController"  sidebar="false" showHeader="true" showChat="false" recordSetVar="exp" >
<script src="../../soap/ajax/30.0/connection.js" type="text/javascript"></script>
<apex:form >

<apex:inlineEditSupport />

<apex:pageBlock title="List of Expenses">
<apex:pageBlockTable value="{!exp}" var="item" >
<apex:column value="{!item.Date__c}"/>

<apex:column value="{!item.Type__c}"/>
<apex:column value="{!item.Amount__c}"/>
<apex:column value="{!item.Comments__c}"/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:commandButton action="{!save}" value="Save" id="theButton1" onclick="alert('Saving the changes...')"/>
<apex:commandButton value="Total" id="theButton2" onclick="alert('Displaying the total...')"/>

</apex:form>
</apex:page>

My Controller Extension Class :

public with sharing class ExpenseController
{

private ApexPages.StandardSetController sc;
public Integer SumOfAllExpenses = 0;

public ExpenseController(ApexPages.StandardSetController sc)
{
this.sc = sc;
displayTotal();
}


public void displayTotal()
{

List<AggregateResult> i = [SELECT SUM(Amount__c) FROM Expense__c];
SumOfAllExpenses = Integer.valueOf(i[0].get('expr0'));
}

public PageReference save()
{

sc.save();
PageReference p = new PageReference('/apex/addExpenses');
return p;

}


}

My requirement :

Display data of the member variable (SumOfAllExpenses) from ExpenseController class in the pop up of

<apex:commandButton value="Total" id="theButton2" onclick="alert('Displaying the total...')"/>

Can someone tell me how to achieve it ?

0

1 Answer 1

1

You need to make the value available by having a getter in the controller. One common pattern to use is this get using lazy initialization (remove the displayTotal method);

public Integer SumOfAllExpenses {
    get {
        if (SumOfAllExpenses == null) {
            List<AggregateResult> i = [SELECT SUM(Amount__c) FROM Expense__c];
            SumOfAllExpenses = Integer.valueOf(i[0].get('expr0'));
        }
        return SumOfAllExpenses;
    }
    private set;
}

The value is then be made part of the JavaScript string when the Visualforce generates the HTML page:

onclick="alert('Sum of all expenses is {!SumOfAllExpenses}')"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.