You need to sign in to do that
Don't have an account?
Trigger not updating
I am trying to update the parent opportunity record with a count of all child records that meet a specified criteria when a new child custom object is created or modified. I have checked the SOQL queries and they are returning the results I expected. The opportunity relationship field is present and required.
trigger UpdatePendingPOMRequests on DM__c (after insert, after update) {
//Find ID for 'POM' Record Type
RecordType rt = [Select r.Id from RecordType r WHERE r.name = 'POM' AND r.SobjectType = 'DM__c'];
for(DM__c dm : trigger.new){
if(dm.RecordTypeId == rt.id){
integer dmct = [Select Count()
FROM DM__c d
WHERE dm__c.dm_opportunity_id__c = :dm.dm_opportunity_id__c
AND dm__c.RecordTypeId = :rt.id
AND dm__c.POM__c = 'Pending'
];
Opportunity oid = [Select Num_Pending_NSP__c from Opportunity WHERE id =:dm.dm_opportunity_id__c ];
oid.Num_Pending_NSP__c = dmct;
Database.upsert(oid);
}
}
}
Thanks, in advance for your response.
Jasonrtaylor,
try the below code and check if it works.
*** I did not add exception handling in the code.
All Answers
Hi Jasonrtaylor,
Before getting into the solution, I think that the functionality that you are trying to implement in the trigger can be done using standard salesforce functionality using the roll-up summary fields.
Create a roll-up summary field on opportunity and select roll-up type as "Count" and filter criteria as "Only records meeting certain criteria should be included in the calculation" and give your critera for record type name = 'pom' and Pom__c = 'Pending'.
If you are not able to access all the fields in the roll-up summary field filter criteria, create formula field "DM Pending Count" in DM object which returns TRUE if RecordType = 'Pom' and POM__c = 'Pending'. Then in the roll-up summary field filter criteria, just refer "DM Pending Count" = TRUE.
Hope this helps.
*** TIP : When writing apex, never use the DML statements inside for loop. Instead add the record to a list and insert the list outside for loop.
If we had the luxury of a Master-Detail relationship, that would definitely be the solution. Since this is just a lookup relationship, we are relegated to a trigger.
I am aware of the DML Limits on Triggers, and I will "Bulkify" the trigger after it is functioning as expected.
Thank you.
-Jason
Jasonrtaylor,
try the below code and check if it works.
*** I did not add exception handling in the code.
This worked great!!!. Thank you.