You need to sign in to do that
Don't have an account?
Tanu
Trigger which will calculate the total amount of those opportunity which is associated to a custom object record.
Hi All,
I have created a lookup field named "oap" on opportunity. Now i need to calculate the total amount of those opportunities which is associated with a particular oap. could you please help me writing a trigger for this as i am new to apex.
Thank you.
Regards
Tanu
I have created a lookup field named "oap" on opportunity. Now i need to calculate the total amount of those opportunities which is associated with a particular oap. could you please help me writing a trigger for this as i am new to apex.
Thank you.
Regards
Tanu
Please refer this link.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm
Trigger calculateTotalAmount on Opportunity (after insert, after update)
{
//It will hold the customObjectIDs
Set<Id> setCustomObjectID = new set<Id>();
list<account> updateCustomObject = new list<account>();
for(Opportunity opp : Trigger.New)
{
setCustomObjectID.add(opp.customObject__c);
}
//run the query to sum the data
AggregateResult[] totalAmountResult= [SELECT SUM(TotalAmountField)sum,CustomObjectId FROM Opportunity group by ROLLUP (CustomObjectId)];
//loop over the result set.
for(AggregateResult ar: totalAmountResult)
{
Id thisCustomObjectId = string.valueOf(ar.get('CustomObjectId'));
CustomObject__c CO = new CustomObject__c(Id=thisCustomObjectId);
CO.totalAmount__c = double.valueOf(ar.get('sum'));
updateAccounts.add(CO);
}
update updateCustomObject;
}
Kindly replace customObject with your object and its fields with your fields name.
Hope this helps you out.
Mark it as best.
Thanks,
Shamsi.
Thanks for your timely response.
I have created a custom field "Tcv" on Opportunity which should calculate (Amount of that oppty/Amount of all optys associated with oap)*100. and that Tcv field should automatically updated on each opty record.
How can i calculate this in trigger.
Thanks
Tanu
You have a custom field TCV on opportuinty.
Everytiime when opportunity is created you want to update this TCV field on Opportunity with total amount of all amount associated with your custom object . Am i Correct ?
Please find attached the screenshot. Hope it helps.
{
//It will hold the customObjectIDs
Set<Id> setOppID = new set<Id>();
list<account> updateCustomObject = new list<account>();
for(Opportunity opp : Trigger.New)
{
setOppID.add(opp.Id);
}
//run the query to sum the data
AggregateResult[] totalAmountResult= [SELECT SUM(TotalAmountField)sum FROM Opportunity where id in : setOppID];
double sumOfAmount = double.valueOf(totalAmountResult.get('sum');
for (Opportunity opp2 : Trigger.New){
opp2.totalAmount__c = opp2.totalAmount__c / (sumOfAmount * 100);
}
Hope this helps you out.
Mark it as best.
Thanks,
Shamsi.