1

I have some related records to a parent record. I want to loop trough the child records and set a checkbox on the first record/index to true and all the other records to false.

How do I achieve this? Something similar to:

(h.Relatie_Contacten__r).size() for(integer x=0; x<(h.Relatie_Contacten__r).size(); x++) If(x=0) {checkbox=true}else..

Loop:

for(Huishouden__c h : [SELECT id, (SELECT id, Contactpersoon__r.Birthdate FROM Relatie_Contacten__r WHERE id IN : rcList ORDER BY Contactpersoon__r.Birthdate ASC)FROM Huishouden__c] ) {
        for(Relatie__c rc : h.Relatie_Contacten__c) {

            }  
        }
2

You just need a variable to keep track if it's the first record or not:

for(Huishouden__c h: [select ... ]) {
  Integer index = 0;
  for(Relatie__c rc: h.Relatie_Contacten__r) {
    rc.First_Record__c = 0 == index++;
  }
}

This works because on the first loop, 0 == index will be true, and then the ++ postfix operator will increment index to 1. For each subsequent loop, 0 == index will be false.

| improve this answer | |
  • So simple, but effective. Thanks! – Thomas May 24 '18 at 0:20
  • @Thomas You're welcome! Always glad to help. – sfdcfox May 24 '18 at 0:28
-2

You could also use the following method

for(Huishouden__c h : [SELECT id,...FROM Huishouden__c] ) {

    for(Integer cnt = 0; cnt <= h.Relatie_Contacten__r.size(); cnt++) {

         h.Relatie_Contacten__r.CheckFlag__c = (cnt > 0) ? false : true;
    }  
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.