0

I wrote code for inserting 6 contacts on iteration basics. I got error unexpected token 'public'.Please help me, I can't find the error in this code.

public class ContactHandler
{
    public void List<Contact> getContacts() {
        List<Contact> contactlist = new List<Contact>;
        for ( Integer count = 1; count<=5; count++) {
            contactlist.LastName = ('Richie' + count);
            contactlist.Phone = 9876543210;
        }

    }
    Insert contactlist;
    return contactlist;
}
ContactHandler ContactObject = new ContactHandler();
ContactObject.getContacts();

How to set the values for sobjects using forloop.

1
  • looks like you're executing all the lines from developer console, usually you create apex class then invoke the call from developer console.
    – Raul
    Jun 2 '20 at 13:10
4

Instantiate a new contact object and add values to it and add it to the list like below

Check this link

for ( Integer count = 1; count<=5; count++) {
            contact eachContact = new contact();

            eachContact.LastName = ('Richie' + count);
            eachContact.Phone = 9876543210;
           contactlist.add(eachContact); 
        }
insert contactlist;

As pointed out by nbrown Added answer for the comments part: Phonenumber field is alpha numeric so put it in quotes.

eachContact.Phone = '9876543210';
4
  • Thanks @RedDevil. Now, its working. But, I got illegal integer error for eachContact.phone = 9875475668; and when I change it as eachContact.phone='9875475668' ; it accepted. What is the difference between these codes.
    – Richie
    Jun 2 '20 at 13:21
  • @Richie, phone number fields in Salesforce are not treated as a number data type, they are strings because they could have leading zeroes and alpha characters in them. developer.salesforce.com/docs/atlas.en-us.api.meta/api/…
    – nbrown
    Jun 2 '20 at 14:01
  • Thanks Brown.Now, I am clear.
    – Richie
    Jun 3 '20 at 10:27
  • @Richie - you may want to mark this as correct answer for the benefit of community. no pressure though
    – RedDevil
    Jun 3 '20 at 10:50

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.