0

I have a Purchase related list under a Custom Object. This related list has all the details of the purchases made Like "Name", "Amount","Purchase Date" etc..

This related list has a Custom button Upload. Once records are approved,when users clicks on the button, all the records will get updated to other Custom Object related list on the same Account layout.

So here I am able to insert every record in to the related. I want to summarize them instead of showing all records. For eg: In the Purchase related list if it has 4 records with same Name - ABC and Amount=300. Once the user upload. Only one record with ABC should get inserted with Amount 1200 .

Is it possible ?

Here is the part of code:

public ID AccId {get;set;}
public Purchase__c pur{get;set;}
//constructor
public className(ApexPages.StandardSetController controller){
    AccId=ApexPages.currentPage().getParameters().get('id');
}
public PageReference addPurchase(){
    List<ApprovedData__c> apd = new List<ApprovedData__c>();

    List<Purchase__c> plist = [Select Id, Name,Amount__c,PurchaseDate__c,Company__c from Purchase__c where Account__C=:AccId];

    for(Purchase__c pur: plist){

        ApprovedData__c ap=new ApprovedData__c();
        ap.PName__c=pur.Name;
        ap.pAmount__c=pur.Amount__c;

        apd.add(ap);
    }


    insert apd;
}
else{
    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'NO DATA FOUND');
    ApexPages.addMessage(errormsg);
    return null;
}
2
  • And how would you roll up PurchaseDate__c for records whose name is the same?
    – Adrian Larson
    Commented Sep 29, 2016 at 18:45
  • @AdrianLarson The Purchase related list Names will be same. Sorry for adding purchase date,that is old code. I updated my code
    – Learner
    Commented Sep 29, 2016 at 18:49

1 Answer 1

0

I suggest you simply use a Map<String, Decimal> to store the results and convert that to a List<ApprovedData__c> at the end.

Map<String, Decimal> amounts = new Map<String, Decimal>();
for (Purchase__c purchase : purchases)
{
    if (!amounts.containsKey(purchase.Name))
        amounts.put(purchase.Name, purchase.Amount__c);
    else
        amounts.put(purchase.Name, amounts.get(purchase.Name) + purchase.Amount__c);
}

List<ApprovedData__c> records = new List<ApprovedData__c>();
for (String name : amounts.keySet())
    records.add(new ApprovedData__c(PName__c=name, PAmount__c=amounts.get(name));
insert records;

You should also look into proper error handling.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .