I started writing some code using apex functions and then I thought let's try it out with Javascript remoting.
Remoting method was called from my VF page and all worked fine, until I tried to use local variable inside the remoting method. Here is my class:
global class MyClass
{
public static List <Account> accounts {get; set;}
public void init()
{
accounts = [SELECT Id, Name FROM Account];
}
@RemoteAction
global static Account findAccount(String accountName)
{
for(Account acc : accounts)
{
if(acc.Name == accountName)
return acc;
}
return new Account();
}
}
This is the code in my VF page:
var accountName = 'Test';
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.MyClass.findAccount}',
accountName,
function(result, event)
{
if (event.status)
{
console.log(result);
}
else if (event.type === 'exception')
{
alert('Error');
}
else
{
alert('Error');
}
},
{escape: true}
);
When I debug the "accounts" in the remoting method, the list is empty. Is there anything that I'm missing here?
I have tried making the list static too and accessing it by referencing the class name but still no luck.
Please note that this is a simple example, the actual code is a bit different and the init method is called from the VF page through the action parameter of the page tag.
Appreciate your help!