public List<Account> accresults {get;set;}
public List<Account> getAccounts(Integer NumberOfRecords){
List<Account> accountList = [SELECT Id FROM Account where Status__c = 'Open' Limit 5];
Map<Id, Account> selectedAccountsMap = new map<Id, Account>();
Account account;
List<Account>accResults = new List<Account>();
Integer rand;
Integer count = accountList.size();
//Integer numberOfRecordsToSelect = 25;
Integer i = 1;
while (i <= NumberOfRecords){
rand = randomWithLimit(count);
System.debug('Random Number: ' + rand);
account = accountList[rand];
if(selectedAccountsMap.get(account.Id) == null)
{
selectedAccountsMap.put(account.Id, account);
i++;
}
}
accresults.addAll(selectedAccountsMap.values());
system.debug(accresults);
return accresults;
}
public static Integer randomWithLimit(Integer upperLimit){
Integer rand = Math.round(Math.random()*1000);
return Math.mod(rand, upperLimit);
}
1 Answer
A few starting points:
- You can rewrite your method greatly to operate using a dynamic limit
- You can directly call the results of an soql query into a map (Although there seems to be no reason to use a map here, since you later add only the values to a list of accounts)
- If you are calling this method from a visualforce page, you won't be able to pass along the
NumberOfRecords
parameter from the page, you'll have to use theapex:param
tag. - You likely don't want to return the values themselves, but instead, want to return something to rerender the page, as opposed to the data, if your data is set somewhere in the controller.
Your method can look like this instead of what you have in your post:
public Integer NumberOfRecords { get; set; }
public List<Account> accountResults { get; set; }
public PageReference getAccounts() {
if (NumberOfRecords > 5) {
NumberOfRecords = 5;
}
accountResults = [SELECT Id FROM Account where Status__c = 'Open' Limit :NumberOfRecords];
return null;
}
And you can use it in visualforce as such:
<apex:commandButton action="{!getAccounts}" reRender="someBlock">
<apex:param value="5" assignTo="{!NumberOfRecords}" />
</apex:commandButton>
<!-- .... -->
<apex:outputPanel id="someBlock">
<apex:repeat value="{!accountResults}" var="a">
<p>{!a.Name}</p>
</apex:repeat>
</apex:outputPanel>
As an aside, I'd highly recommend the Visualforce Trailhead to get you accostomed to working with the laungauge.
LIMIT 5
in your query, but also iterate over the results to reduce the number to theNumberOfRecords
parameter? Why not just pass the number to your query withLIMIT :NumberOfRecords
return null;
at the end ofgetAccounts()
is probably your culprit (or a big part of it at the very least). There may be other semantic issues withgetAccounts()
as well. Can you go into more detail about exactly what you are hoping to accomplish with this method?