Blog

Query List view Records from Apex & Lightning Comp

Innovalleyworks

One of the coolest features provided Force.com API to fetch metadata via REST api calls.

The below list of challenges are covered in this blog.

  1. Calling Self org REST API from apex
  2. Using List view metaData
  3. Accessing Session ID from lightning Component

My business scenario is to fetch the list of contacts and create Meeting attendee records for a particular meeting.
I don’t want to search or use filter or custom UI. I want to leverage the Salesforce out of the box feature to fetch and process list of Contacts.

Salesforce has list view features to filter the contacts and display them in list view.
We can leverage this listview and fetch the records of list view to process from lightning component.

Salesforce metadata API helps to fetch the list view Query and then we can use the Query to fetch records.

String listViewId = ‘AnyContact listview ID’;
System.debug(‘The listViewId–>’ + listViewId);
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
String endPoint = URL.getSalesforceBaseUrl().toExternalForm()+’/services/data/v45.0/sobjects/Contact/listviews/’+listViewId+’/describe’;
System.debug(‘The End Point–>’ + endPoint);
req.setEndpoint(endPoint);
req.setHeader(‘Authorization’, ‘Bearer ‘ + getUserSession());
req.setHeader(‘Content-Type’, ‘application/json’);
req.setMethod(‘GET’);
req.setTimeout(20000);
String resp, query;
res = http.send(req);
resp = res.getBody();
ListViewOption lt = (ListViewOption)JSON.deserialize(resp, ListViewOption.class);
query = lt.query;
List
contacts = Database.query(query);

The toughest part is getting the Session ID from lightning Component. The lightning component call to Apex method does not support UserInfo.getSessionID() method.
So we need to build a work around to bring Session ID.

We can build a VF page and call the page and getbody of the page from Apex code under Aura enabled method. Now we are able to get the Session ID from VF page.

Apex method to Call from Aura Method

public static String getUserSession(){
// Refer to the VF Page built with Body contains Session ID
PageReference reportPage = Page.SessionIDPage;
// Get the content of the VF page
String vfContent = reportPage.getContent().toString();
System.debug(‘vfContent ‘+vfContent);
Integer startP = vfContent.indexOf(‘Session_ID_Start’) + ‘Session_ID_Start’.length(),
Integer endP = vfContent.indexOf(‘Session_ID_End’);
String sessionId = vfContent.substring(startP, endP);
System.debug(‘sessionId ‘+sessionId);
return sessionId;
}

VF Page

Session_ID_Start{
!$Api.Session_ID}
Session_ID_End

We are Innovalleyworks , We are a passionate team of developers, best thinkers and consultants who can solve anything and everything.
With our highly engaging team, you can easily bring the vision to all your business ventures come true.
We have team, put your problem, get your solution