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!
Best Answer
There are a couple of things.
If you put all that together, this should get you at least a working example.
Note, that this will infact requery the database everytime findAccounts is called. A design pattern I like to use, and have seen a lot looks something like the following:
This will ensure that the query is only run once within the lifespan of the request.
You also may want to utilize a
Map<String, Account> accountNameToAccountMap
see Apex Maps, so that you can avoid iterating through the list every single time. But, I'll leave that as an exercise.