Get Listview Records | Listview filters and Query in Apex
Sometimes it is very needed to get Listview records. But what if you get all Listview fields and filters. With this method you can get listview fields, filter, sorting order and even query too.
This method uses the REST API to make a callout and fetch the listview data. To get all these listview data you need to pass listview Id and sObject name to it. Listview Id can be easily fetched by querying on Listview object. You can use the below query to get Listview Id.
1 2 3 |
[SELECT Id, Name, DeveloperName, SobjectType FROM ListView] |
Here you can pass your listview name in the WHERE condition of the query to get your specific listview Id. You also need to pass your session Id into it as it is s REST API callout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void getListviewFilters(String filterId, String objectName) { HttpRequest req = new HttpRequest(); String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); String endPoinURL = baseUrl+'/services/data/v50.0/sobjects/'+ objectName +'/listviews/'+ filterId +'/describe'; req.setEndpoint(endPoinURL); req.setMethod('GET'); req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); Http http = new Http(); HttpResponse response = http.send(req); if( response.getStatusCode() == 200 ) { Map<String, Object> tokenResponse = (Map<String, Object>) JSON.deserializeUntyped(response.getBody()); String query = (String) tokenResponse.get('query'); System.debug(query); } } |
Here, to get another data you need to iterate tokenResponse variable. This variable will provide you the below data.
So this way you can easily fetch Listview records, fields, filters, and query. Also, the sort filters.
If you want to get records directly, you can use the below endpoint in this method. But fetching records using this have some limits. You can check out more information here.
1 2 3 |
String endPoinURL = baseUrl+'/services/data/v50.0/sobjects/'+ objectName +'/listviews/'+ filterId +'/results'; |
Also Check:
For any queries or suggestions, comment below.
Cheers … Happy Coding … 🙂
In the Get Listview Records | Listview filters and Query in Apex, how can I use it on visual force page and get the related items from this list view?
Hi Imran,
Put this Apex method in your VisualForce Page Controller or Extension (whichever you are using) and pass the Listview Id and Object Name in it. You can get Listview Id by querying on Listview Object. Use tokenResponse.get(‘columns’) to get fields list and store it in a {get; set;} type variable and use it on your page.