Sunday, July 2, 2017

Listview in Apex in salesforce and with test class:


How to access ListView in Apex | Using standardSetController for Pagination

There are scenario in project lifecycle where developer creates SOQL or Dynamic SOQL to return expected result. Also if requirement changes they go back and change existing code to reflect updated SOQL. If you are good developer and avoid to change Apex code at most you will save your SOQL in “Custom Settings” and utilize in Dynamic SOQL.
However, There is very good design Developer can suggest to client. Instead of going to your code and changing code for new requirement, how it sounds if we can utilize existing List View inside Apex or Visualforce only ðŸ™‚ ? It will solve lots of problems and if requirement changed, just change or create new Listview and it will reflect in your Visualforce code. We can almost have same functionality like Navigation buttons and Paging without writing any complex code logic, thanks to StandardSetController capabilities.
There is also very good article on Salesforce blog on various approaches suggested for pagination and one of them is using StandardSetController.
To keep article simple, I am posting complete Visualforce and Apex code with Comments inside. Account object is used as an example here.

Use ListView in Visualforce with Paging and Navigation
Use ListView in Visualforce with Paging and Navigation

Apex class :
1/**
2*  Description : Controller Class to show How to utilize existing List View in Apex with Pagination Support
3*
4*  Author : Jitendra Zaa
5*/
6public with sharing class ListViewDemo {
7
8  private String baseQuery = 'Select ID, Name FROM Account ORDER BY NAME ASC';
9  public String AccFilterId {get; set;}
10  private Integer pageSize = 10;
11
12  public ListViewDemo(){}
13
14  public ApexPages.StandardSetController AccSetController {
15        get{
16            if(AccSetController == null){
17                AccSetController = newApexPages.StandardSetController(Database.getQueryLocator(baseQuery));
18                AccSetController.setPageSize(pageSize);
19
20                // We have to set FilterId after Pagesize, else it will not work
21                if(AccFilterId != null)
22                {
23                  AccSetController.setFilterId(AccFilterId);
24                }
25            }
26            return AccSetController;
27        }set;
28    }
29
30  public ListViewDemo(ApexPages.StandardSetController c) {   }
31
32    //Navigate to first Page
33    public void firstPage()
34    {
35      AccSetController.first();
36    }
37
38    //Navigate to last Page
39    public void lastPage()
40    {
41      AccSetController.last();
42    }
43
44    //Navigate to Next page
45    public void next()
46    {
47      if(AccSetController.getHasNext())
48      {
49        AccSetController.next();
50      }
51    }
52
53    //Navigate to Prev Page
54    public void prev()
55    {
56      if(AccSetController.getHasPrevious())
57      {
58        AccSetController.previous();
59      }
60    }
61
62    public List<Account> getAccounts()
63    {
64      return (List<Account>)AccSetController.getRecords();
65    }
66
67    //Get all available list view for Account
68    public SelectOption[] getAccountExistingViews(){
69        return AccSetController.getListViewOptions();
70    }
71
72    /**
73    * Reset List View
74    */
75    public PageReference resetFilter()
76    {
77      AccSetController = null;
78        AccSetController.setPageNumber(1);
79        return null;
80    }
81
82}
Visualforce Page:
1<apex:page controller="ListViewDemo">
2Available List Views for Account :
3  <apex:form id="pageForm">
4       <apex:selectList value="{!AccFilterId}" size="1" id="filterMenu">
5            <apex:selectOptions value="{!AccountExistingViews}"></apex:selectOptions>
6            <apex:actionSupport event="onchange"  action="{!resetFilter}" rerender="AccntTable"status="ajaxStatus"/>
7       </apex:selectList>
8
9       <apex:actionStatus id="ajaxStatus" startText="Loading..."  stopText=""/>
10
11     <apex:pageBlock title="Accounts">
12        <apex:pageBlockButtons >
13                <apex:commandButton action="{!firstPage}" value="|<<" reRender="AccntTable"  status="ajaxStatus" />
14                <apex:commandButton action="{!prev}" value="<" reRender="AccntTable"  status="ajaxStatus" />
15                <apex:commandButton action="{!next}" value=">" reRender="AccntTable"  status="ajaxStatus" />
16                <apex:commandButton action="{!lastPage}" value=">>|" reRender="AccntTable"  status="ajaxStatus" />
17            </apex:pageBlockButtons>
18
19            <apex:pageBlockTable value="{!Accounts}" var="item" id="AccntTable">
20                <apex:column value="{!item.name}"/>
21            </apex:pageBlockTable>
22     </apex:pageBlock>
23   </apex:form>
24</apex:page>
Test Class :
1@isTest
2public class ListViewDemoTest
3{   
4     
5    @testSetup
6    static void createAccount() {
7        // Create common test accounts
8        List<Account> testAccts = new List<Account>();
9        for(Integer i=0;i<20;i++) {
10            testAccts.add(new Account(Name = 'TestAcct'+i));
11        }
12        insert testAccts;       
13    }
14     
15     public static testMethod void getListView(){
16        //Lets Assume we are writing Controller extension to use on List View of Account
17        List <Account> acctList = [SELECT ID FROM Account];
18         
19         //Check Account created count by setup()
20         System.assertEquals(20,acctList.size());
21          
22        //Start Test Context, It will reset all Governor limits
23        Test.startTest();
24
25        //Inform Test Class to set current page as your Page where Extension is used
26        Test.setCurrentPage(Page.ListViewDemo);
27
28        //Instantiate object of "ApexPages.StandardSetController" by passing array of records
29        ApexPages.StandardSetController stdSetController = newApexPages.StandardSetController(acctList);
30
31        //Now, create Object of your Controller extension by passing object of standardSetController
32        ListViewDemo ext = new ListViewDemo(stdSetController);
33         
34        SelectOption[] selOptions = ext.getAccountExistingViews();
35          
36        //We should not assert count of list View as no control over creation of list view
37        //but in my Dev org, I know count is 6
38        System.assertEquals(6,selOptions.size());
39          
40         ext.firstPage();
41         List<Account> accFirsttPage = ext.getAccounts();
42         System.assertEquals( 10, accFirsttPage.size() );
43          
44         ext.next();
45         ext.prev();
46         ext.resetFilter();
47         ext.lastPage();
48           
49        //Finish Test
50        Test.stopTest();
51     }
52}

No comments:

Post a Comment