+ Start a Discussion
SoozeeSoozee 

Trigger to update a different custom object

trigger Trigger_Name on CustomObject__c (after insert) {
List<CustomObject__c> emailList = [select id from CustomObject__c where ID in :trigger.newMap.keyset()];
List<OtherCustomObject__c> recordsToUpdate = new List<OtherCustomObject__c>{};

for(CustomObject__c e: emailList){

for(OtherCustomObject__c le : e.letter__r.id ){
le.emailed__c=true;
le.date_emailed__c = datetime.now();
lettersToUpdate.add(le);
} 

update lettersToUpdate; 
}
}

Hello - I would like to update a field in one object based on the creation of a record in aother object.

 

I get this error when I try to save:  

Save error: Loop must iterate over a collection type: Id 

 

Help?

 

Best Answer chosen by Admin (Salesforce Developers) 
New_DeveloperNew_Developer

Try this

Assuming that the CustomObject__c has a lookup relation to OtherCustomObject__c

trigger Trigger_Name on CustomObject__c (after insert) {

Set<id> lids = new Set<id>();

List<CustomObject__c> emailList = [select id , letter__c from CustomObject__c where ID in :trigger.newMap.keyset()];

List<OtherCustomObject__c> recordsToUpdate = new List<OtherCustomObject__c>();

for(CustomObject__c e: emailList){

lids.add(e.letter__c);
}

List<OtherCustomObject__c> obj = new List<OtherCustomObject__c>([Select id,emailed__c,date_emailed__c from OtherCustomObject__c where id IN :lids]);

for(OtherCustomObject__c le : obj ){
le.emailed__c=true;
le.date_emailed__c = datetime.now();
recordsToUpdate.add(le);

}
update recordsToUpdate;
}
}

All Answers

New_DeveloperNew_Developer

Is there any relation between the two objects??

New_DeveloperNew_Developer

Try this

Assuming that the CustomObject__c has a lookup relation to OtherCustomObject__c

trigger Trigger_Name on CustomObject__c (after insert) {

Set<id> lids = new Set<id>();

List<CustomObject__c> emailList = [select id , letter__c from CustomObject__c where ID in :trigger.newMap.keyset()];

List<OtherCustomObject__c> recordsToUpdate = new List<OtherCustomObject__c>();

for(CustomObject__c e: emailList){

lids.add(e.letter__c);
}

List<OtherCustomObject__c> obj = new List<OtherCustomObject__c>([Select id,emailed__c,date_emailed__c from OtherCustomObject__c where id IN :lids]);

for(OtherCustomObject__c le : obj ){
le.emailed__c=true;
le.date_emailed__c = datetime.now();
recordsToUpdate.add(le);

}
update recordsToUpdate;
}
}

This was selected as the best answer
SoozeeSoozee

Thank you so much!  This worked great!