Sunday 20 August 2017

Custom List View Of SObjects Using SOAP API In Lightning View

Custom List View Of SObjects

This is very useful article to create custom list view in lightning view of any object as defined in standard functionality.
Below is the example to create custom list view-

Now create Apex Class-

Apex Class

public with sharing class ListView
{
    public String sObjectName{get;set;}
    public String sListViewId{get;set;}
    public ListView()
    {
        sObjectName ='Account';  // Set any SObject name here
        sListViewId ='Defualt';     // Set as a default list view.
    }
    
    // Call function via action function from page
    public PageReference viewList()
    {
        return null;
    }
    
    // Get the object which has been selected in SObject in Constructor.
    public List<sObject> getObjectRecord()
    {
        try{
            String query ='Select Name,CreatedDate  from '+sObjectName;
            if(sListViewId !='Default')       // 'sListViewId' contains record Ids.
            {
               query +=' Where ID IN('+ sListViewId +')'; 
            }
            return Database.query(query +' Order by CreatedDate desc LIMIT 30');
        }
        catch(Exception ex)
        {
         System.debug('Error '+ex.getMessage());
        }
        return new List<sObject>();
    }
}

Visualforce Page


<apex:page controller="ListView" showHeader="false" standardStylesheets="false">
  <head>
       <!-- Call Lightning Desgin System(CSS).-->
      <apex:slds />
      <!-- Call jquery from static resource-->
      <apex:includeScript value="{!$Resource.jquery}" /> 
      <style>
        #sellistview {
            width: 375px;
            float: left;
            margin-bottom: 5px;
        }
        #SortView{
            width: 48%;
            float: right;
            margin-bottom: 5px;
            text-align: right;
            padding-right: 24px;

        }
      </style>
      <script>
        // Call the List View API to obtain a list of List Views for the selected object
        $.ajax({
            url : '/services/data/v32.0/sobjects/{!URLENCODE(sObjectName)}/listviews',
            headers : { 'Authorization' : 'Bearer {!$Api.Session_ID}' },
            datatype : 'json',
            success : function(data, textStatus, jqXHR) {
                $("#selectListView")
                        .append($("<option></option>")
                        .attr("value",'Default')
                        .text('Default'));
                $.each(data.listviews, function(index, obj) {
                    $("#selectListView")
                        .append($("<option></option>")
                        .attr("value",obj.id)
                        .text(obj.label));                 
                });
              
            }
        });     
      </script>
      <script>
            function getRecords(listViewId) 
            {
              $('#spinnerView').show();
                if(listViewId =='Default') {
                   getListViewRecords(listViewId);
            }
            else
           {
                 $.ajax({
                url : '/services/data/v32.0/sobjects/{!URLENCODE(sObjectName)}/listviews/' + listViewId + '/results',
                headers : { 'Authorization' : 'Bearer {!$Api.Session_ID}' },
                datatype : 'json',
                success : function(data, textStatus, jqXHR) {                  
                var recordId ='';
                    $.each(data.records, function(rowIndex, record) {
                       $.each(record.columns, function(colIndex, column) {
                            if(!data.columns[colIndex].hidden)
                                recordId = recordId+(recordId =='' ? '\''+record.columns[6].value+'\'':',\''+record.columns[6].value+'\'');
                        });
                    });
                  getListViewRecords(recordId);
                }
            });
       
          } 
        }
        </script>   
  </head>
  <body>
      <apex:form >
          <apex:actionFunction name="getListViewRecords" reRender="lstColumn" action="{!viewList}">
            <apex:param value="" name="sObjListRecordId" assignTo="{!sListViewId}"/>
          </apex:actionFunction>
       <!--Start Header-->
            <div class="slds-page-header" role="banner">
              <div class="slds-media">
                <div class="slds-media__figure">
                </div>
                <div class="slds-media__body">
                  <p class="slds-page-header__title slds-truncate slds-align-middle" title="{!sObjectName}">List View - {!sObjectName}</p>
                  <p class="slds-text-body--small slds-page-header__info">  <apex:outputText value="{0,date,MM/dd/yy}"> <apex:param value="{!Today()}" /> </apex:outputText></p>
                </div>
                <div class="slds-no-flex">
                    <div class="slds-button-group">
                     </div>
                    <div class="slds-media__body">
                      <p class="slds-text-body--small slds-page-header__info" style="font-weight: 600;float: right;" title="Object : {!sObjectName}"> Object : {!sObjectName}</p>
                     
                    </div>
                  </div>
              </div>
            </div>
            <div class="LObjName" id="HeaderDetail" style="margin-top: 10px;">      
            <div id="sellistview">
                View &nbsp;: &nbsp;
                <select id="selectListView" class="slds-select" onChange="getRecords(this.value);" style="width:80%;"></select>
            </div>
            <div id="SortView">  
               <!-- Provide object in select option to use that object functionality-->
               Object Name :<apex:selectList id="Limit" value="{!sObjectName}" size="1" styleClass="slds-select" style="width:20%">
                    <apex:selectOption itemValue="Account" itemLabel="Account"/>
                    <apex:selectOption itemValue="Contact" itemLabel="Contact"/>
                </apex:selectList>
               &nbsp; <apex:commandButton value="Search" StyleClass="slds-button slds-button--neutral slds-button--small"   />
            </div>
          </div>
        <hr></hr>
       <!-- End Header -->
       <!--Start Table records -->
       <apex:outputPanel id="lstColumn">
       <table class="slds-table slds-table_bordered slds-table_cell-buffer">
          <thead>
            <tr class="slds-text-title_caps">
              <th scope="col">
                <div class="slds-truncate" title="sObjectName Name">{!sObjectName} Name</div>
              </th>
              <th scope="col">
                <div class="slds-truncate" title="Close Date">Create Date</div>
              </th>
            </tr>
          </thead>
          <tbody>
           <apex:repeat value="{!ObjectRecord}" var="sObj" >
            <tr>
              <th scope="row" data-label="sObjectName Name">
                <div class="slds-truncate" title="name">{!sObj['Name']}</div>
              </th>
              <td data-label="Account Name">
                <div class="slds-truncate" title="createddate">{!sObj['CreatedDate']}</div>
              </td>
            </tr>
            </apex:repeat>
          </tbody>
        </table>
        </apex:outputPanel>
       <!-- End Table records-->
      </apex:form>
  </body>
</apex:page>



Now lets look on visualforce,
Firstly get the view list on load of page through AJAX of the SObject which you have defined in class like here SObject is Account. 

In Ajax , We get the list view data of sObject by the custom API URL. So
we pass the service api url as end point and then pass authentication in the header and define datatype that which type of data you are getting from end point url in response.

You can select object from the picklist and click 'Search' button then it will set the selected object configuration on page. Like I selected 'Contact ' object then it will populate list view drop down picklist of contact and select value from picklist then 'onChange' event fire and call Javascript function 'getRecord()' and pupulate the data in the table.










0 comments:

Post a Comment

If you have any doubts, please let me know.