0

I am getting an error in the for loop.

Error: Variable does not exist: acclist

public class AddPrimaryContact implements Queueable {
Private Contact conl = new Contact();
Private String sty;
Public List<Contact> coninsert = new List<Contact>();

public AddPrimaryContact(Contact conlist, String str)
{
    this.conl = conlist;
    this.sty= str;
}


public void execute(QueueableContext context)
{
    for(List<Account> acclist: [Select id,name from Account where BillingState =:sty]);
    {
        for(Account accops:acclist)// Error in this statement
        {
            conl.lastname = 'testLast';
            conl.accountid = accops.id;
             coninsert.add(conl);
        }
    }

    if(coninsert.size()>0)
    {
        insert coninsert;
    }
}}
Adrian Larson
  • 149,971
  • 38
  • 239
  • 420
SFDC_BigDog
  • 795
  • 2
  • 19
  • 40

2 Answers2

1

You have two for loops doing the same thing (along with some syntax issues), you only need one of them. You execute method should look like this

public void execute(QueueableContext context)
{

    for(Account accops : [Select id,name from Account where BillingState =:sty])
    {
        conl.lastname = 'testLast';
        conl.accountid = accops.id;
        coninsert.add(conl);
    }

    if(coninsert.size()>0)
    {
        insert coninsert;
    }
}
Chris Duncombe
  • 24,176
  • 11
  • 75
  • 116
-1

Mistake was to write List in first for loop. Only one for-loop is required. Just understand below code.

public class AddPrimaryContact implements Queueable {
    Private Contact conl = new Contact();
    Private String sty;
    Public List<Contact> coninsert = new List<Contact>();

    public AddPrimaryContact(Contact conlist, String str)
    {
        this.conl = conlist;
        this.sty= str;
    }


    public void execute(QueueableContext context)
    {
        // while doing query at forloop, at return List of sObject, and a forloop always iterate over list (collection)
        for(Account accops:[Select id,name from Account where BillingState =:sty])// Correction here : 
        {
            conl.lastname = 'testLast';
            conl.accountid = accops.id;
             coninsert.add(conl);
        }

        if(coninsert.size()>0)
        {
            insert coninsert;
        }
    }
}
Ankuli
  • 670
  • 2
  • 11
  • 27