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
Antoine_LeleuAntoine_Leleu 

Sum the field of related custom obejct

Hello,

 

I tried to write an apex code to sum the field of child related list obect.

 

I have 2 custom objects : "Server__c" and "Component__c"

i have a field, type :number, called "Memory__c" in the component object.

there are n Components related to Server.

 

I would like to sum the Memory of each component related to my server.

 

i tried this, but it doesn't work. I'm new in the apexcode

 

public class CustomserverController {

Id idServer = null;
Integer SumMemory = 0;

public CustomChassisController(ApexPages.StandardController conMain) {
// Set Variables
idServer = conMain.getId();
}

List<Server__c> LstServer = [SELECT (select Memory__c FROM Components__r) FROM Server__c WHERE Id = :idServer];

for(Server__c a: LstServer)
{
for(Components__c o: a.Components__r)
{
SumMemory += Memory__c;
}
}
}

 

Thanks for your help

 

Antoine

 

RustanRustan

Are you trying to sum it and show it in a visualforce page or are you trying to add the sum in a field?

 

If you are trying to add a sum into a field, you may want to use a trigger in the child object to update the parent object.

Antoine_LeleuAntoine_Leleu

 

Hello Rustan,

 

Thanks for your answer.

Actually, i would like show the sum in a custom visualforce page.

 

Antoine

Daniel.ReidDaniel.Reid

Hello,

 

Could you provide a little more information, please? What exactly do you mean by "it doesn't work", what sort of result are you getting? Any errors?  Though, glancing at your code, I noticed that in this block

for(Server__c a: LstServer)
{
   for(Components__c o: a.Components__r)
   {
     SumMemory += Memory__c;
   }
 }

 

"SumMemory += Memory__c;" should be "SumMemory += o.Memory__c;"

 


Let me know if that helps you out.  If not, we can keep looking for a solution.

 

Daniel Reid
Contact us - We can help!

Salesforce Superheroes
------------------------------
help@salesforcesuperheroes.com
www.salesforcesuperheroes.com
1-888-407-9578 x102