Thursday, August 28, 2014

How to do JSON parsing in Apex Visualforce

Ok so today we will be looking into the Json parsing. Json is "Javascript Object Notation" a new form of format which is widle used over the http responce in webservices. It is structured and can contain data in human readable format.

To make json data salesforce provide some standard class called as System.JSON. We will be using this class to parse and then un parse the data in json.

Parsing:

  1. Create a visualforce page with controller.
  2.  Now copy this code to make a wrapper class holding name,id and phone fields
    //Subclass : Wrapper Class 
        public class Accountwrap {
            //Static Variables 
            public string id;
            public string name;
            public string Phone;
            
            //Wrapper  Class Controller
            Accountwrap(string Phone, string name, string id) {
                this.Phone = Phone;
                this.name = name;
                this.id = id;
            }
        }
  3. Now to parse this wrapper class list into a json string use this code.
    public void getlstAccount(){
            List < Accountwrap > lstwrap = new List < Accountwrap > ();
            List < account > lstacc = [SELECT Id, Name, Phone FROM Account limit 2];
            for (Account a: lstacc) {
                Accountwrap awrap = new Accountwrap(a.Phone,a.name,a.id);
                lstwrap.add(awrap);
            }
            strJson = JSON.serialize(lstwrap);
        }
  4. strJson is a public string and will get the json string,
Un-Parsing:
  1. To convert the json string we will use the same wrapper class to provide structure to the values.
  2. To un parse the string use this code
    public static List<Accountwrap> parse(String str) {
            system.debug('*****str*****'+str );
            JSONParser parser = JSON.createParser(str);
            system.debug('*****parse*****'+parser );
            List<Accountwrap> jsonstatLst = new List<Accountwrap> ();
            while (parser.nextToken() != null) { System.debug('Current token: ' +  parser.getCurrentToken() + '****JSONToken.START_ARRAY****'+JSONToken.START_ARRAY);
                if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                    while (parser.nextToken() != null) {
                        // Advance to the start object marker to
                        //  find next invoice statement object.
                        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                            jsonstatLst.add((Accountwrap)parser.readValueAs(Accountwrap.class));
                            parser.skipChildren();
                        }
                    }
                }
            }
            return jsonstatLst;
        }
  3. jsonstatLst is a List of type wrapper class and the method can populate any list of the same type with data in wrapper object form.
Hope this helps you!!

Wednesday, August 27, 2014

How to bootstrap with Visualforce

Ok so today I am going to show you a small and simple example of how to get started with bootstrap in visualforce. Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. So now first thing first:

  1. Download bootstrap lib zip file from "http://getbootstrap.com/" and upload it to your custom setting by name "Bootstrap".
  2. Now create a visualforce page name "Bootstrap_Mobile_CreateAccount".
  3. And include the bootstrap scripts as :

<!-- Load script here -->
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap-theme.min.css')}"/>
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap.min.css')}"/>
    <apex:includeScript value="https://code.jquery.com/jquery.js"/>
    <apex:includeScript value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/js/bootstrap.min.js')}"/>
    4.   Now create div and give the class of bootstrap as shown here
<div class="container">
 <br/>
 <div class="panel panel-primary">
  <div class="panel-heading">
   <h3 class="panel-title">Create Account</h3>
  </div>
  
  <div class="panel-body">
   Details:
   <div class="row">
    <div class="col-md-4"><input id="inp1" type="text" placeholder="Account Name" class="form-control"/></div>
    <div class="col-md-4"><input id="inp2" type="text" placeholder="Description" class="form-control"/></div>
    <div class="col-md-4"><input id="inp3" type="text" placeholder="Phone" class="form-control"/></div>
   </div>
   <br/>
   <br/>
   <button class="btn btn-lg btn-primary btn-block" type="submit" onclick="createAcc();">Save</button>
  </div>
 </div>
</div>
     5.   Now provide this <javaScript> to the page to we can save the records.
<script>
 Visualforce.remoting.timeout = 120000; // Set timeout at page level
 var $j = jQuery.noConflict();        

 function createAcc(){
  $j('#basicModal2').modal('show');
  var accName= $j('#inp1').val();
  var accDes= $j('#inp2').val();  
  var accPhn= $j('#inp3').val();          
  Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Bootstrap_Mobile_CreateAccountCon.createAccount}',accName,accDes,accPhn,handleResult);  
 } 
 function handleResult(result, event){
  if (event.status) {
   alert(result);
  } 
      
 }             
</script>  
6. Now create a controller and in that create this javascriptRemoting method
@RemoteAction
global static string createAccount(String accName, String accDes, String accPhn){
 Account acc = new Account();
 acc.name = accName;
 acc.Description = accDes;
 acc.Phone = accPhn;
 insert acc;
 return 'Success';
}
That is it, You have created a visualforce page that is using bootstrap css for view and apex controller for saving the records.

PS: For different type of element you can use different class as:
CheckBox:
<div class="checkbox col-md-4">
 <label>
   <input type="checkbox"> Check Box</input>
 </label>
</div>
//get the checkbox values as this or you can also get a array of objects and use .each
//for multiple checkboxes id starting with inp4
function checkId(){
   var inpVal= $j('#inp4').prop('checked');
   alert(inpVal);
}

Hope this helps you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      

vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new
Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
  for(string s: displayFieldLst){          
    clm = new Component.Apex.column(headerValue= '' + s + '');         
    outText = new Component.Apex.OutputText();          
    outText.expressions.value = '{!row[\'' + s + '\']}';         
    clm.childComponents.add( outText );      
    datatable.childComponents.add( clm );
  }  
  outPanel.childComponents.add( datatable );
}

What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      
vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
for(string s: displayFieldLst){          
clm = new Component.Apex.column(headerValue= '' + s + '');         
outText = new Component.Apex.OutputText();          
outText.expressions.value = '{!row[\'' + s + '\']}';         
clm.childComponents.add( outText );      
datatable.childComponents.add( clm );
}  
outPanel.childComponents.add( datatable );
}
What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

Wednesday, August 20, 2014

How to use Salesforce to Salesforce

Salesforce to Salesforce or commonly known as S2S is a data migration feature that is provided as OOB by Salesforce.com. When there is a requirement for data to be moved from one Salesforce Org to another then without using any third party tools as CastIron or Sap BODS we can move data. The idea is to provide a near runtime integration between org. Some points to consider when implementing S2S:


  •  You cannot publish fields that you do not have permission to edit.
  • Only some of the standers objects and all custom objects are permitted to send data.
Follow these steps to enable and configure S2S:

  1. Go to App Setup > Customize > Salesforce to Salesforce > Settings and click enable.

Tuesday, August 19, 2014

How to use "System.RunAs" in test class

Ok so few times we are facing a challenge that a piece of code that we are covering in test must be run under only for some specific users. in this case we can use "System.RunAs" to over come the limitations, here is an example so we can pass it:

// This code runs as the admin user
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
User u = new User(Alias = 'tadmins', Email='testAdmin2014@testorg.com', 
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
LocaleSidKey='en_US', ProfileId = p.Id, 
TimeZoneSidKey='America/Los_Angeles', UserName='testAdmin2014@testorg.com');
System.runAs(u) {
// here the code for test class
}

Hope this helps you!!

Thursday, August 14, 2014

How to get date based on fiscal year,quarter or month

Date startDate = [Select StartDate From Period Where type = 'Quarter' and StartDate = THIS_FISCAL_QUARTER].StartDate;

Date startDate = [Select StartDate From Period Where type = 'Month' and StartDate = THIS_FISCAL_Month].StartDate;

Date startDate = [Select StartDate From Period Where type = 'Year' and StartDate = THIS_FISCAL_Year].StartDate;

The above will get you the current start date for the custom fiscal year.
Note: Custom fiscal year has to be setup if you want any results.

Thursday, August 7, 2014

How to play video in visualforce from attachment

So we have developed many data driven pages but when it comes to multimedia then many of us didn't worked on it much. We are thing "Ok its just a video or a image I will display it by getting its path" but the problem arise when its(the MIME file) is an attachment. Attachments are stored in database unlikely if compared from static resource which has a direct access URL. So how can I display a multimedia file if its type is BLOB.

The answer is here, we can use <object> tag or we can have <video> tag of HTML5.
for <object> tag, here the {!crwAtt.id} is Attachment object.
hor <video> tag, remember to add "docType="html-5.0"" to page.

Tuesday, August 5, 2014

How to use escape sequences with SOQL

So you are trying to pass some quoted string in a SOQL query and hits a error as some thing like this "line break not allowed". Now to over come this you can use the escape sequence provided by salesforce. What it really does is that when ever a string ends by single quote then salesforce mark it as a non break sequence, but when you introduce another quote then it breaks the single string into two if "+" is not used. Ok fare enough but if we need more then one quote then it will be very diffycult to add all those "+" signs. So to do this we can use the below methods:

\n or \N New line
\r or \R Carriage return
\t or \T Tab
\b or \B Bell
\f or \F Form feed
\" One double-quote character
\' One single-quote character
\\ Backslash
LIKE expression only: \_ Matches a single underscore character ( _ )
LIKE expression only:\% Matches a single percent sign character ( % )

Example: database.query('Select Id from Account where Id IN ('0019000000txvCQ','0019000000txvCQ')'); wont work

database.query('Select Id from Account where Id IN (\'0019000000txvCQ\',\'0019000000txvCQ\')'); will work