0

While studying doing some exercises, I created an Account with 1000 Contacts related to this account.

My problem is, there the Number_field__c in the Contact Obj. What I need to do is populate the Number_field__c just to 1 to 5. When is 6, it needs to get back to 1 and so on.

I've tried many forms but I`m stuck with something like this:

Account acc = new Account(Name='Dependentes');
insert acc;

List<Contact> conList = new List<Contact>();

for(Integer i = 1; i <= 1000; i++) {

    Integer n = 0;
    Contact c = new Contact();
    c.LastName = 'Contato ' + i;
    c.AccountId = acc.Id;
    c.Number_field__c  = i; 
    conList.add(c); 
}  
insert conList;

As far as I could get.

1

You can use Math.mod for this, which returns the remainder after division:

c.Number_field__c  = 1+Math.mod(i,5); 

The method Math.mod returns a value from 0 to the second parameter minus 1, so we add 1 to get a number from 1 to 5.

As a side note, to get the first account to start at 1, you'd rather start from zero in your loop:

for(Integer i = 0; i < 1000; i++) {

This is the usual way you'd build a loop, since arrays are zero-indexed.

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.