
I am trying to update a field on a grandparent object (Opportunity__c) from a grandchild object (whenever a grandchild object is inserted - there will only ever be one), (Sales_Invoice_Payment__c). The directly related object to (Opportunity__c) is (Sales_Invoice__c).
Please help - my code example and problem I am encountering is below.
trigger OpptyUpdatePaid on Sales_Invoice_Payment__c (after insert, after delete) {
Set<Id>qualifiedIds = new Set<Id>();
for (Sales_Invoice_Payment__c p : Trigger.isDelete ? Trigger.old : Trigger.new ) {
//NEED TO FIND related Sales_Invoice__c and then find the related Opportunity__c
//THIS IS WRONG: trying to find related Oppty ID from parent object
//i also know this is a for within a for and don't know how to fix it
//for (Sales_Invoice__c i : [Select Opportunity__c, Id FROM Sales_Invoice_Payment__c])
//then we will then update a field called Paid on the related Oppty
if (i.Opportunity__c != null) {
qualifiedIds.add(i.Opportunity__c);
}
}
List <Opportunity> opportunitiesToUpdate = new List <Opportunity>();
if (qualifiedIds.size() > 0)
{
// Query for Opptys that are in the wrong state and update them
for (Opportunity o : [Select Paid__c, Id FROM Opportunity WHERE Id IN:qualifiedIds])
{
if(Trigger.isDelete && o.Paid__c == True)
o.Paid__c = False;
else if(Trigger.isInsert && o.Paid__c == False)
o.Paid__c = True;
opportunitiesToUpdate.add(o);
}
}
if(opportunitiesToUpdate.size()>0)
try{
update opportunitiesToUpdate;
}catch(DMLException e){
for(Opportunity o: opportunitiesToUpdate)
{
o.addError(e.getMessage());
}
}
}

Hello, I've tried your code above, David, but now I am receiving this error: "Illegal assignment from List<Sales_Invoice_Payment__c> to Set<Id>" Please see code here:
trigger OpptyUpdatePaid on Sales_Invoice_Payment__c (after insert, after delete) {
set<id> qualifiedIds = new set<id>();
set<id> salesInvoicePaymentId = new set<id>();
if (Trigger.isDelete)
{
salesInvoicePaymentId = [select Sales_Invoice__c from Sales_Invoice_Payment__c where id in :trigger.oldmap.keyset()];
}
else
{
salesInvoicePaymentId = [select Sales_Invoice__c from Sales_Invoice_Payment__c where id in :trigger.newmap.keyset()];
}
qualifiedIds = [select opportunity__c from Sales_Invoice__c where id in :salesInvoicePaymentId];
List <Opportunity> opportunitiesToUpdate = new List <Opportunity>();
if (qualifiedIds.size() > 0)
{
// Query for Opptys that are in the wrong state and update them
for (Opportunity o : [Select Paid__c, Id FROM Opportunity WHERE Id IN:qualifiedIds])
{
if(Trigger.isDelete && o.Paid__c == True)
o.Paid__c = False;
else if(Trigger.isInsert && o.Paid__c == False)
o.Paid__c = True;
opportunitiesToUpdate.add(o);
}
}
if(opportunitiesToUpdate.size()>0)
try{
update opportunitiesToUpdate;
}catch(DMLException e){
for(Opportunity o: opportunitiesToUpdate)
{
o.addError(e.getMessage());
}
}
}