+ Start a Discussion
Rob LilleyRob Lilley 

Select lastest record in an apex class


I wonder if anyone could advise as have very limited knowledge of Apex. We use Salesforce to give out grants and mainly built around Accounts and Opportunities (renamed to Requests). We have a button on the request which populates two fields on the request:

Previous Grants (long text, rich text format)  (a listing of the grants previous to this request for an account) eg:
2010-2011  £3,000
2012-2013  £2,500

Previous Grants Total (currency)  - the total of all the grant amounts for this account previous to this request.

This all work well. In addition I would now last to have an extra fields that shows just the last grant. Eg 2012-2013  £2,500

Is this possible? I guess it would be in the Select statement somewhere? I have copied the code below.

Many thanks for any help in advance, Rob

global class PopulatePreviousGrantsController {
    webService static String populatePreviousGrants(Id oppId) {
       try {
            List<String> args = new String[]{'0','number','###,###,##0.00'};
            List<Opportunity> currentOppList=[SELECT Id,Decision_Date__c,AccountId FROM Opportunity WHERE Id= :oppId ];
            List<Opportunity> oppList=[SELECT Id,Grant_Payment_Period__c,Grant_Amount__c,Previous_Grants_Total__c,Decision_Date__c,CreatedDate FROM Opportunity WHERE AccountId = :currentOppList.get(0).AccountId AND Decision_Date__c <= :currentOppList.get(0).Decision_Date__c ORDER BY Decision_Date__c];
            String previousGrants='';
            Decimal previousGrantsTotal=0;
            if(oppList != NULL && oppList.size() > 0) {
                for(Opportunity opp :oppList) {
                    if(opp.Grant_Amount__c > 0 && opp.Id != oppId) {
                        String period=opp.Grant_Payment_Period__c == NULL ? '' :opp.Grant_Payment_Period__c;
                        previousGrants+=period+'&nbsp;&nbsp;&nbsp;&pound;'+String.format(opp.Grant_Amount__c.format(), args)+'<br>';
            Opportunity opp=new Opportunity();
            update opp;
            return 'Success'; 
        }catch(Exception e) {
            System.debug('<--------------ERROR LOG------------------>'+e);
            return e.getMessage();