Wednesday, 31 May 2017

Query data in javascript - VF Page

In this blog i will explain how we can extract data in javascript on visualforce page.
Recently I came across a requirement where i need to create picklist with more 3000 records to display on a visualfoce page. 
The picklist values were saved as custom setting records. As we all are aware that in visualforce picklist, the maximum limit options allowed are 1000.
To insert more than 1000 options we can use javascript.
First we need to include script which allow us to perform soql query in javascript
<script src="/soap/ajax/9.0/connection.js" type="text/javascript">
Now on window.onload function we will first get the current session ID.
The session ID will be used to connect to salesforce database in javascript.
sforce.connection.sessionId = '{!$Api.Session_ID}';
after getting the session we will do the query using sforce.connection.query to perform query.
After retrieving the records we need to convert it into array of records to perform operation.
var records = qr.getArray("records");
After receiving the record we will loop on the record and create Option element dynamically.
After creating the element we will append it to a Select element using append child method.
var selectList = document.getElementById('SelectList');
for(var i=0;i<records.length;i++)
           {
               
               var x = document.createElement("Option");
               x.innerHTML     = records[i].IATA_Code__c+' - '+records[i].Full_Name__c+' '+records[i].Country__c;
                x.value         = records[i].IATA_Code__c;
                selectList.appendChild( x );
           }
As we know that by using sforce.query.connection we can only retrieve upto 2000 records, to
get more records we will have a look in below record.
var selectList = document.getElementById('airport-codes');
            alert(selectList)
            sforce.connection.sessionId = '{!$Api.Session_ID}';
            var qr = sforce.connection.query("select Id, IATA_Code__c, ICAO_Code__c, 
           Full_Name__c, City__c, State__c, Country__c FROM Airport_Code__c 
          WHERE IATA_Code__c != Null AND IATA_Code__c != \'\' ORDER BY IATA_Code__c");
            var queryMore = true;
            while (queryMore) {
            var records = qr.getArray("records");
           for(var i=0;i<records.length;i++)
           {
               
               var x = document.createElement("Option");
               x.innerHTML     = records[i].IATA_Code__c+' - '+records[i].Full_Name__c+' '+records[i].Country__c;
                x.value         = records[i].IATA_Code__c;
                selectList.appendChild( x );
           }
           if (qr.getBoolean("done")) {
                queryMore = false;
            }
            else {
                qr = sforce.connection.queryMore(qr.queryLocator);
            }
          }
after retrieving the record using sforce.connection.query, getboolean("done") method return true if all the records are retrieved from database.
if there are more records then the method will return false. in the above code we are using while loop untill the getboolean() returns true.
if the value is false then we will use queryMore method to retrieve next batch of records from database. 
This process continue till all the records are retrieved.
Wrapper class, as name suggests, is used for wrapping two types of data together and make them to work as single record.

For example, let's take a sample scenario to understand the wrapper class.
User wants to display account records along with checkboxes on VF page.
User should be able select more than one record and work on them.
In this scenario we will fetch account records and wrap them with checkbox.

In this example we will display list of accounts with checkboxes. select those records we want to update and click on update button. All selected record's name will be appended by 1.
//Sample Class for wrapper
Public class wrapperSample
{
 public list<Account> acc{get; set;}
 public list<wrapperAction> wrapper {get; set;}

 public wrapperSample()
 {
   acc = new list<account>();
   wrapper = new list<wrapperAction>();
   acc = [select id, name from account limit 10];
   for(account a : acc)
   {
     wrapper.add(new wrapperAction(a)); //Sending records to wrapper class
   }
 
 }

 // Creating wrapper records of accounts with a boolean variable flag
 public class wrapperAction
 {
   public boolean flag{get; set;}
   public account acc{get; set;}
   public wrapperAction(account a)
   {
     acc = a;
flag = false;
   }
 }
 //Updating the name of accounts selected on VF page
 public void recordUpdate()
 {
   list<account> updateAccounts = new list<Account>();
 
   for(wrapperAction wr: wrapper)
   {
     if(wr.flag)
{
  wr.acc.name = wr.acc.name+' 1';
  updateAccounts.add(wr.acc);
}
 
   }
 
   update updateAccounts;
 }

}



//Visualforce page to display the records with checkbox

<apex:page controller="wrapperSample">
  <apex:form id="form">
   <apex:pageBlock >
    <apex:pageBlockTable value="{!wrapper}" var="wr">
     <apex:column >
      <apex:inputcheckbox value="{!wr.flag}" />
     </apex:column>
     <apex:column value="{!wr.acc.id}"/>
     <apex:column value="{!wr.acc.name}"/>
    </apex:pageBlockTable>
    <apex:commandButton value="Update" action="{!recordUpdate}" rerender="form"/>
   </apex:pageBlock>

  </apex:form>
</apex:page>



Once the update is done all the selected records name will get appended by 1 As shown in figure.


The above is a simple scenario of wrapper class. Similarly in many complex scenario's also wrapper class is used to achieve functionality in less code.

Create record in lightning

With the advancement of lightning, we are getting introduced to new features of lightning that helps in creating a better functionality in ...