Monday, 27 April 2015

Pagination using standardsetcontroller in salesforce


StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list controllers provided by Salesforce

You can instantiate a StandardSetController in either of the following ways:
  • From a list of sObjects:
    List<account> accountList = [SELECT Name FROM Account LIMIT 20];
    ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);
  • From a query locator:
    ApexPages.StandardSetController ssc = 
    new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM Opportunity]));


Visual force page

<apex:page controller="CustomPaginationController" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!acc.Name}" label="Name"/> 
                <apex:inputText value="{!acc.Phone}" label="Phone" />
            </apex:pageblockSection>
        </apex:pageBlock>
        <apex:pageBlock id="resultId" rendered="{!if(lstAccount != null && lstAccount.size > 0, true,false )}">
            <apex:pageBlockButtons >
                <div style="text-align:right"> 
                  Total Records Found: {!Con.resultSize}  
 <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>  
 <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>  
 <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>  
 <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>           
 <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>           
 <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;  
 <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>  
 <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/> 
 <img src="/s.gif" title="Last Page" alt="Last Page" class="last"/>         
                </div>
            </apex:pageBlockButtons>                
            <apex:pageBlockSection columns="1">
                <apex:pageBlockTable value="{!lstAccount}" var="acc" >
                    <apex:column value="{!acc.Name}"/>
                    <apex:column value="{!acc.Phone}"/>
                </apex:PageblockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>



Apex Class

public with sharing class CustomPaginationController 
{
    public Account acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public CustomPaginationController ()
    {
       acc = new Account();
       lstAccount = new List<Account>();
    }
    public List<Account> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Account>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Phone != null && (acc.Phone).trim() !='' )
        {
           if(strFilter == '')
           { 
               strFilter  = strFilter  +  ' where Phone like \''+acc.Phone+'%\'' ;
           }
           else
           {
               strFilter  = strFilter  +  ' And Phone like \''+acc.Phone+'%\'' ;
           }
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, phone from Account '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(2);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;  
    }  
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  
    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  
    public void previous()  
    {  
        con.previous();  
    }  
    public void next()  
    {  
        con.next();  
    }  
   
}



Thanks,
Amit Chaudhary

Thursday, 9 April 2015

Visualforce page life cycle in salesforce

When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by the server. The order in which these elements are executed can affect how the page is displayed to the user

There are two types of Visualforce page requests:


  1. A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.
  2. A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action.


Order of Execution for Visualforce Page Get Requests

A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a get request:



In the diagram above the user initially requests a page, either by entering a URL or clicking a link or button. This initial page request is called the get request.

  1. Constructor methods on the associated controller / extension classes are called, instantiating the controller objects.
  2. If the page contains any custom components, they are created and the constructor methods on any associated custom controllers or controller extensions are executed. If attributes are set on the custom component using expressions, the expressions are evaluated after the constructors are evaluated.
  3. The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method calls, such as getting or setting a property value, are made.
  4. If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.
  5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser executes them.

As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods.

Once a new get request is made by the user, the view state and controller objects are deleted

Note:-  If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a postback request is made. When a postback request is made, the view state is maintained

Constructor of controller /extension - >  constructor of custom components  -> AssignTo any Custom Components -> Action method->Getter or Setter -> Form method -> HTML

Order of Execution for Visualforce Page Postback Requests

A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a postback request:



  1. During a postback request, the view state is decoded and used as the basis for updating the values on the page.
  2. After the view state is decoded, expressions are evaluated and set methods on the controller and any controller extensions, including set methods in controllers defined for custom components, are executed.
  3. The action that triggered the postback request is executed. If that action completes successfully, the data is updated. If the postback request returns the user to the same page, the view state is updated
  4. The resulting HTML is sent to the browser
If the postback request indicates a page redirect and the redirect is to a page that uses the same controller and a proper subset of controller extensions of the originating page, a postback request is executed for that page. Otherwise, a get request is executed for the page. If the postback request contains an <apex:form> component, only the ID query parameter on a postback request is returned

NOTE :- Once the user is redirected to another page, the view state and controller objects are deleted.


Thanks,
Amit Chaudhary

Sunday, 5 April 2015

Model View Controller (MVC) paradigm salesforce

Model view controller (MVC) is a software architecture pattern which separates the representation of information from the user’s interaction with it.

MVC pattern in salesforce contains below three modules:
  1. Model
  2. View
  3. Controller
1) A controller can send commands to its associated view to change the view’s presentation of the model . It can also send commands to the model to update the model’s state. According to Salesforce : How the interface actions. Controllers are used to perform the actions whenever users interact with visual force.

2) A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. A passive implementation of MVC omits these notifications, because the application does not require them or the software platform does not support them. According to salesforce :- What schema and data does salesforce uses to represent the system completely. In salesforce, we can say that sObjects are the model as every entity in salesforce is mapped to some sObject.

3) A view requests from the model the information that it needs to generate an output representation.
According to Saleforce :- How the schema and data is represented. Visualforce is used to present the data to users.


M - Model (Object, Fields, Relationships, Apex Classes)
V - View (Visualforce page, Pagelayouts, Record Types, Force.com Sites, Components)
C - Controller(Validation Rules, Controllers in a Visualforce page)

Some Useful link :- https://developer.salesforce.com/page/An_Introduction_to_Visualforce

Thanks,
Amit Chaudhary

Wednesday, 1 April 2015

External Data Sources with Lightning Connect OData 2.0

External Data Sources

Create external data sources to connect Salesforce to outside systems, such as SharePoint or any other data base.

Prerequisite
1) XML file for External Data Source



Step 1:- From Setup, click Develop | External Data Sources.


Step 2 :- Click New External Data Source, or click Edit to modify an existing external data source.



Step 3 :- Complete the specific steps for your data source.


Step 4 :- Click Validate and Sync, and confirm that the connection gets a successful status

Step 5 :- Optionally, select tables and click Sync to do the following for each selected table




Link :- https://www.youtube.com/watch?v=4aChUHMI5I8


Sunday, 15 March 2015

Type of Sandbox in salesforce


Developer Sandbox
Developer sandboxes are special configuration sandboxes intended for coding and testing by a single developer. Multiple users can log into a single Developer sandbox, but their primary purpose is to provide an environment in which changes under active development can be isolated until they’re ready to be shared. Just like Developer Pro sandboxes, Developer sandboxes copy all application and configuration information to the sandbox. Developer sandboxes are limited to 200 MB of test or sample data, which is enough for many development and testing tasks. You can refresh a Developer sandbox once per day.

REFRESH LIMIT    :-  Daily
DATA LIMIT          :-  200MB


Developer Pro Sandbox
The main difference between this and Developer is the amount of data that can be stored.  It also grabs some product data from production.  If those two things are important, use this one.  Otherwise, it's interchangeble with Developer

Developer Pro sandboxes copy all of your production organization's reports, dashboards, price books, products, apps, and customizations under Setup, but exclude all of your organization's standard and custom object records, documents, and attachments. Creating a Developer Pro sandbox can decrease the time it takes to create or refresh a sandbox from several hours to just a few minutes, but it can only include up to 1 GB of data. You can refresh a Developer Pro sandbox once per day

REFRESH LIMIT    :-  Daily
DATA LIMIT          :-  1GB


Partial Copy
Partial Data sandboxes include all of your organization’s metadata and add a selected amount of your production organization's data that you define using a sandbox template. A Partial Data sandbox is a Developer sandbox plus the data you define in a sandbox template. It includes the reports, dashboards, price books, products, apps, and customizations under Setup (including all of your metadata). Additionally, as defined by your sandbox template, Partial Data sandboxes can include your organization's standard and custom object records, documents, and attachments up to 5 GB of data and a maximum of 10,000 records per selected object. A Partial Data sandbox is smaller than a Full sandbox and has a shorter refresh interval. You can refresh a Partial Data sandbox every 5 days.

REFRESH LIMIT    :-  5 Days
DATA LIMIT          :-  5GB


Full Sandbox
Full sandboxes copy your entire production organization and all its data, including standard and custom object records, documents, and attachments. You can refresh a Full sandbox every 29 days.
Sandbox templates allow you to pick specific objects and data to copy to your sandbox, so you can control the size and content of each sandbox. Sandbox templates are only available for Partial Data or Full sandboxes.

REFRESH LIMIT    :-  29 Days
DATA LIMIT          :-  Same as Production





Wednesday, 11 March 2015

how to stop recursive trigger in salesforce

Problem :-  

1) Many Developers face recursive trigger , or recursive update trigger. For example in 'after update' trigger, Developer is performing update operation and this lead to recursive call.

2) You want to write a trigger that creates a new record ; however, that record may then cause another trigger to fire, which in turn causes another to fire, and so on. 

 
Solution :-

you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.


 Apex Class with Static Variable

public class ContactTriggerHandler
{
     public static Boolean isFirstTime = true;
}


Trigger Code

trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>(); 
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test') 
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }
}


Thursday, 5 March 2015

Locking Statements FOR UPDATE

Apex allows you to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety problems. While an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user interface.

Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

NOTE:-
  1. While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other clients have to wait until the transaction completes and the records are no longer locked before being able to update the same records. Other clients can still query the same records while they’re locked.
  2. If you attempt to lock a record currently locked by another client, you will get a QueryException. Similarly, if you attempt to update a record currently locked by another client, you will get a DmlException.
  3. If a client attempts to modify a locked record, the update operation might succeed if the lock gets released within a short amount of time after the update call was made. In this case, it is possible that the updates will
 You can’t use the ORDER BY keywords in any SOQL query that uses locking

Thanks,
Amit Chaudhary