You need to sign in to do that
Don't have an account?
Help needed with the trigger
Hi ,
Help needed with the below code.
The custom field 'Actual_Number_Of_Sales__c' on Sales_Target__c should get updated with the count number based on the certain condition as mentioned below in the code.
trigger afterTrigger on Sales_Target__c (after insert){
Sales_Target__c[] newRecords = trigger.new;
set<id> salesTargetId = new set<id>;
for(Sales_Target__c salesTarget : newRecords){
salesTargetId.add(salesTarget.id);
Integer sales = [select count() from Sales_Opportunity__c where Count_Against_Targets__c = true AND
Sales_Target__c IN : salesTargetId AND status__c = 'Closed Won'];
salesTarget.Actual_Number_of_Sales__c = sales;
Integer calls = [select count() from Task where Count_Against_Targets__c = true AND Sales_Target_ID__c IN : salesTargetId];
salesTarget.Actual_Number_of_Calls__c = calls;
}
Norte: There is an anothet object called Sales_Opportunity__c which has a lookup relationship to the Sales_Target__c object.
When iam trying to create and save a record on Sales_target__c ,its giving me the below erroe on the lines highlited in red.
Apex trigger SalesTargetTrigger caused an unexpected exception, contact your administrator: SalesTargetTrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only:
Any help is appreciated..
Thanks
I changed the code instead like this as shown below
for(Sales_Target__c st2 : newRecords) {
AggregateResult[] salesgroupedResults = [select count(Name) cou,Count_Against_Targets__c , Sales_Target__c
from Sales_Opportunity__c where Count_Against_Targets__c = true AND status__c = 'Closed Won' AND Sales_Target__c = :st2.id
GROUP BY Count_Against_Targets__c , Sales_Target__c
];
for (AggregateResult ar : salesgroupedResults) {
st2.Actual_Number_Of_Sales__c = Integer.valueOf(ar.get('cou'));
}
}
Even then the Actual_Number_Of_Sales__c is not getting updated with count.
Need help in modifying the code
Thanks
Change the trigger to be before the insert. It's very easy to work with a trigger like that:
You don't even need to do an update.