Jun 10

Pagination using standard set controller salesforce

Pagination using standard set controller salesforce

We can use Standard set controllers provided by salesforce to implement pagination in visualforce. It is very easy to implement pagination using standard set controller. We can easily navigate through pages, move directly to first, last page or to next or previous pages using standard set controller. We can also decide how many records should be displayed in every page. We need to instantiate the StandardSetController and use the standard methods provided by salesforce to leverage the pagination functionality.

In example below we are displaying all opportunities in visualforce page with pagination. We have specified default page size 10.

Click for Demo

Pagination using standard set controller salesforce

Visualforce Page:

<apex:page controller="OpportunitiesPaginationController" tabStyle="Opportunity">
    <apex:form >
        <apex:actionFunction name="refreshPageSize" action="{!refreshPageSize}" status="fetchStatus" reRender="pbId"/>
        <apex:pageBlock id="pbId">
            <apex:pageBlockSection title="All Opportunities" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!Opportunities}" var="oppObj">
                    
                    <apex:column headerValue="Opportunity Name">
                        <apex:outputField value="{!oppObj.Name}"/>
                    </apex:column>
                    
                    <apex:column headerValue="Account Name">
                        <apex:outputField value="{!oppObj.Account.name}"/>
                    </apex:column>
                    
                    <apex:column headerValue="Amount">
                        <apex:outputField value="{!oppObj.Amount}"/>
                    </apex:column>
                    
                    <apex:column headerValue="Stage">
                        <apex:outputField value="{!oppObj.StageName}"/>
                    </apex:column>
                    
                    <apex:column headerValue="Last Activity Date">
                        <apex:outputField value="{!oppObj.LastModifiedDate}"/>
                    </apex:column>
                    
                    <apex:column headerValue="Close Date">
                        <apex:outputField value="{!oppObj.CloseDate}"/>
                    </apex:column>
                </apex:pageBlockTable>
                
                <apex:panelGrid columns="8"> 
                
                <apex:selectList value="{!size}" multiselect="false" size="1" onchange="refreshPageSize();">
                    <apex:selectOptions value="{!paginationSizeOptions}"/>
                </apex:selectList>
                
                <apex:commandButton status="fetchStatus" reRender="pbId" value="First" action="{!setCon.first}" disabled="{!!setCon.hasPrevious}" title="First Page"/> 
 
                <apex:commandButton status="fetchStatus" reRender="pbId" value="Previous" action="{!setCon.previous}" disabled="{!!setCon.hasPrevious}" title="Previous Page"/> 
 
                <apex:commandButton status="fetchStatus" reRender="pbId" value="Next" action="{!setCon.next}" disabled="{!!setCon.hasNext}" title="Next Page"/> 
 
                <apex:commandButton status="fetchStatus" reRender="pbId" value="Last" action="{!setCon.last}" disabled="{!!setCon.hasNext}" title="Last Page"/> 
 
                <apex:outputText >{!(setCon.pageNumber * size)+1-size}-{!IF((setCon.pageNumber * size)>noOfRecords, noOfRecords,
                     (setCon.pageNumber * size))} of {!noOfRecords}
                </apex:outputText> 
                      
                <apex:outputPanel >                      
                    <apex:actionStatus id="fetchStatus" >
                        <apex:facet name="start" >
                          <img src="/img/loading.gif" />                    
                        </apex:facet>
                    </apex:actionStatus>
                </apex:outputPanel> 
 
            </apex:panelGrid>  
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class OpportunitiesPaginationController{
    Public Integer size{get;set;} 
    Public Integer noOfRecords{get; set;} 
    public List<SelectOption> paginationSizeOptions{get;set;}
        
    public OpportunitiesPaginationController(){
        size=10;
        paginationSizeOptions = new List<SelectOption>();
        paginationSizeOptions.add(new SelectOption('5','5'));
        paginationSizeOptions.add(new SelectOption('10','10'));
        paginationSizeOptions.add(new SelectOption('20','20'));
        paginationSizeOptions.add(new SelectOption('50','50'));
        paginationSizeOptions.add(new SelectOption('100','100'));
    }
    
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {                
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select id,Name,AccountId,Account.name,Amount,StageName,CloseDate,LastModifiedDate from Opportunity]));
                setCon.setPageSize(size);  
                noOfRecords = setCon.getResultSize();
            }            
            return setCon;
        }
        set;
    }
    
    //Changes the size of pagination
    public PageReference refreshPageSize() {
         setCon.setPageSize(size);
         return null;
    }

    // Initialize setCon and return a list of record    
    
    public List<Opportunity> getOpportunities() {
         return (List<Opportunity>) setCon.getRecords();
    }
}
 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/pagination-using-standard-set-controller-salesforce/

Feb 15

Avoid recursive trigger in salesforce

Avoid recursive trigger in salesforce using static variable

Avoid recursive trigger in salesforce using static variable

Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output.

It is very common to have recursion in trigger which can result to unexpected output or some error. So we should write code in such a way that it does not result to recursion. But sometime we are left with no choice.

For example, we may come across a situation where in a trigger we update a field which in result invoke a workflow. Workflow contains one field update on same object. So trigger will be executed two times. It can lead us to unexpected output.

Another example is our trigger fires on after update and it updates some related object and there is one more trigger on related object which updates child object. So it can result too infinite loop.

To avoid these kind of situation we can use public class static variable.

In RecursiveTriggerHandler class, we have a static variable which is set to true by default.

Read the rest of this entry »

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/avoid-recursive-trigger-salesforce/

Oct 24

get current record id salesforce

get current record id salesforce

apexpages.currentpage().getparameters().get(‘id’) can be used to get current record id or other url parameters in apex code.

Many times we have requirement to get current record id or url parameters of visualforce page in apex code.

Many times we require the current record id in controller. For example we are redirecting from one visualforce page to another visualforce page using apex code and we have also set some parameters for second visualforce page. Then, in that case we can use apexpages.currentpage().getparameters().get(‘id’) to get parameter with id name or any other name.

One more example if we have a button on detail page overridden by visualforce page and once the button is pressed you require the id(or the other field values of that record) of the record from whose detail page the button was clicked. For this requirement also we can use ApexPages.CurrentPage().getparameters().get(‘id’) to get other parameters.

In the following example we will use a custom extension to get current record id and one parameter with name nameParam. Then we are using one visualforce page to display current record id and all fields related to that record id by querying using SOQL query and also displaying value of one more parameter with name nameParam. In this way we can get value of any parameter in Apex code.

Click for Demo

get current record id salesforce

Visualforce Page:

<apex:page standardController="Account" extensions="CurrentRecordIdDemoController">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection title="Current account record Id is : {!currentRecordId}" collapsible="false">
            <apex:outputField value="{!acc.name}"/>
            <apex:outputField value="{!acc.AccountNumber}"/>
            <apex:outputField value="{!acc.Type}"/>
            <apex:outputField value="{!acc.Industry}"/>
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Testing parameter" collapsible="false">
            Name is <b>{!parameterValue}</b>
        </apex:pageBlockSection>
        
    </apex:pageBlock>
  </apex:form>
</apex:page>

Apex Code:

public class CurrentRecordIdDemoController{
public String currentRecordId {get;set;}
public String parameterValue {get;set;}
public Account acc{get;set;}

    public CurrentRecordIdDemoController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        acc = [select id ,name, AccountNumber, Type, Industry from Account where id =: currentRecordId ];
        parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
    }
}
 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/get-current-record-id-salesforce/

Permanent link to this article: http://www.sfdcpoint.com/salesforce/migration-using-ant-in-salesforce/

Jun 20

actionstatus visualforce disable screen

actionstatus visualforce disable screen

actionStatus visualforce component displays the status of an AJAX update request. An AJAX request can either be in progress or complete.

Depending upon the AJAX request status (whether AJAX request is in progress or complete), this component will display different message to user. In many scenarios AJAX request takes some time. So we should display some message to user that your request is in progress. Once request is complete, we can display some different message to user.

Using actionstatus, we can also display some gif (graphic Interchange Format), which shows to user that their request is in progress. It gives very good presentation to end user.

In the example below, we are using actionStatus for commandbutton. We are showing account edit page to user. When user will click on save buttton, request will go to controller method. We are showing gif image to user while AJAX request is in progress using actionstatus component. We are using apex:facet tag inside actionstatus to show image and we have specified name value as ‘start’ in apex:facet tag. So It will show image when request is in progress. We can also use ‘stop’ value in name attribute of apex:facet to specify message when request completes.

Click for Demo

actionstatus visualforce disable screen

Visualforce Page:

<apex:page controller="actionStatusImage" tabStyle="Account">
    <apex:outputpanel >
        <apex:actionstatus id="actStatusId">
            <apex:facet name="start">
                <div class="waitingSearchDiv" id="el_loading" style="background-color: #DCD6D6;
                       height: 100%;opacity:0.65;width:100%;"> 
                    <div class="waitingHolder" style="top: 74.2px; width: 91px;">
                        <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
                        <span class="waitingDescription">Saving...</span>
                    </div>
                </div>
            </apex:facet>
        </apex:actionstatus>
    </apex:outputpanel>
    <apex:form id="formId">
    <apex:pageBlock id="pgBlckId" title="New Account">
        
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save" reRender="pgBlckId" status="actStatusId"/>
        </apex:pageBlockButtons>
        
        <apex:pageBlockSection id="pgBlckSecId" title="Account Information" collapsible="false">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.Phone}"/>
            <apex:inputField value="{!account.Type}"/>
            <apex:inputField value="{!account.Rating}"/>
            <apex:inputField value="{!account.Industry}"/>
            <apex:inputField value="{!account.site}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class actionStatusImage {
    public Account account{get;set;}
    public actionStatusImage(){
        account = new Account();
    }
    public Pagereference save(){
        //upsert account;
        return null;
    }
}
 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/actionstatus-visualforce-disable-screen/

Jun 19

custom label in apex code salesforce

custom label in apex code salesforce example

We can use System.Label.labelName to access custom label in apex code.

Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName

New Custom Label

Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

After creating custom label we can use following code to use custom label in apex code.

Visualforce Page:

<apex:page controller="CustomLabelApexDemoController">
   <apex:form >
     <apex:pageblock >
       Value stored in custom label is: <b>{!customLabelValue}</b>
     </apex:pageblock>
   </apex:form>
</apex:page>
public class CustomLabelApexDemoController {
    public string customLabelValue{get;set;}
    public CustomLabelApexDemoController(){
        customLabelValue = System.Label.DemoLabel;
    }
}

If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom apex code which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in apex code.

String customLabelValue = System.Label.myName.DemoLabel;

We can also use custom label in visualforce page. For more details check this post.

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/custom-label-in-apex-code-salesforce/

Jun 18

custom label in visualforce page

custom label in visualforce page salesforce

We can use $Label global variable to access custom label in visualforce page.

Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in visualforce page using $Label global variable.

New Custom Label

Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

After creating custom label we can use following code to use custom label in visualforce page

Click for Demo

Visualforce Page:

<apex:page tabStyle="Account">
   <apex:form >
     <apex:pageblock >
       <apex:outputText value="Value stored in Demo custom label is : "/>
       <apex:outputText value="{!$Label.DemoLabel}" style="font-weight:bold"/>
     </apex:pageblock>
   </apex:form>
</apex:page>

If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom visualforce page which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in Visualforce page.

<apex:outputText value="{!$Label.myName__DemoLabel}" style="font-weight:bold"/>

We can also use custom label in apex code. For more details check this post

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/custom-label-in-visualforce-page/

Jun 18

Trigger on Attachment in Salesforce

Trigger on Attachment in Salesforce

Many times I have seen question from others that how can we write trigger on attachment in salesforce. For the Attachment, ContentDocument and Note standard objects, we can’t create a trigger in the Salesforce user interface. For these objects, we can create a trigger using development tools, such as the Developer Console or the Force.com IDE. Alternatively, we can also use the Metadata API.

In this example we will learn to write trigger on attachment object in salesforce. Firstly I will explain using developer console. Here are steps to create trigger on attachment using developer console.

1. Click on your name at (top left corner) and Select “Developer Console”

developer console

2. Go to File -> New -> Apex Trigger.

Debeloper Console 2

3. Select name of SObject and enter name of trigger

developer console3

4. Click on submit button. In this way we can create trigger on attachment.

In similar way we can also create trigger using force.com IDE.

We should be very careful while writing the trigger on Attachment, as it will be used by all standard or custom Object on which attachment is added. We should provide criteria to run trigger so that trigger should be executed for required objects only.

In this example I will create the trigger which will check for the parent object “Account”. If the object is Account then it will update one field on account record.

Trigger Code:

trigger AttachmentTriggerDemo on Attachment (before insert) {
    List accountList = new List();
    Set accIds = new Set();
    for(Attachment att : trigger.New){
         //Check if added attachment is related to Account or not
         if(att.ParentId.getSobjectType() == Account.SobjectType){
              accIds.add(att.ParentId);
         }
    }
    accountList = [select id, has_Attachment__c from Account where id in : accIds];
    if(accountList!=null && accountList.size()>0){
        for(Account acc : accountList){
            acc.has_Attachment__c = true;
        }
        update accountList;
    }
}
 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/trigger-on-attachment-in-salesforce/

May 04

SOSL Example in Salesforce

SOSL Example in Salesforce


SOSL – Salesforce Object Search Language

SOSL is a search language in salesforce and the important feature is that Unlike SOQL, we can search in multiple objects at same time using SOSL. In SOQL, we can query only one object at a time but in SOSL, We can search for some specified string like ‘testString’ in multiple objects at the same time.

  • We can search for some specified string like ‘testString’ in multiple objects at the same time.
  • We can mention in which fields of all the sObjects,we want to search for the string specified.
  • The SOSL query start with the keyword ‘FIND’.
  • You can specify, which fields to return for each object mentioned in SOSL query. Suppose you have performed search on three objects Account, Contact & Opportunity. Then you can mention like, for list returned with Account results only (Name, Industry) fields should be returned, and for Contacts results (firstName, lastName) should be returned and similarly for Opportunity.
  • The result of SOSL is a list of lists of sObjects “List<List<sObject>>”.
  • The returned result contains the list of sObjects in the same order as order mentioned in SOSL  query.
  • If a SOSL query does not return any records for a specified sObject type, then search results include an empty list for that sObject.
  • The search string should be at least two characters long.

Here is the quick demo SOSL Demo

SOSL-Example-in-Salesforce

Below is the sample code that has a input text box and a command button which will search for the entered string in three Object . i.e Accounts, Contacts, Opportunities and returned result will be shown in the page block tables.

<apex:page controller="SOSLController">
  <apex:form >
  <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslDemo_method}"                reRender="acct,error,oppt,cont" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
                <apex:facet name="start" >
                    <img src="/img/loading.gif"/>                    
                </apex:facet>
    </apex:actionStatus>
  </apex:form>

    <apex:outputPanel title="" id="error">
     <apex:pageMessages ></apex:pageMessages>
     </apex:outputPanel>

    <apex:pageBlock title="Accounts" id="acct">
    <apex:pageblockTable value="{!accList }" var="acc">
          <apex:column value="{!acc.name}"/>
          <apex:column value="{!acc.Type}"/>
       </apex:pageblockTable>
    </apex:pageBlock>

 <apex:pageBlock title="Contacts" id="cont">
    <apex:pageblockTable value="{!conList}" var="con">
      <apex:column value="{!con.name}"/>
      <apex:column value="{!con.email}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
 
 <apex:pageBlock title="Opportunities" id="oppt">
    <apex:pageblockTable value="{!optyList}" var="opty">
      <apex:column value="{!opty.name}"/>
     <apex:column value="{!opty.StageName}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
  
</apex:page>

Below is the controller for the same

Public with sharing class SOSLController{
 Public List<Opportunity> optyList {get;set;}
 Public List<contact> conList{get;set;}
 Public List<account> accList{get;set;}
 
 Public String searchStr{get;set;}
   Public SOSLController(){
   }
 
  Public void soslDemo_method(){
   optyList = New List<Opportunity>();
   conList = New List<contact>();
   accList = New List<account>();
   if(searchStr.length() > 1){
   String searchStr1 = '*'+searchStr+'*';
   String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
   List<List <sObject>> searchList = search.query(searchQuery);
   accList = ((List<Account>)searchList[0]);
   conList  = ((List<contact>)searchList[1]);
   optyList = ((List<Opportunity>)searchList[2]);
   if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
       apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
       return;
   }
   }
   else{
   apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least two characters..'));
   return;
   }
  }
}

For more information and possibilities in SOSL, please Click Here

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/sosl-example-in-salesforce/

Apr 19

SOQL query in javascript example

SOQL query in javascript example

You can use SOQL in java-script on your VF pages or any kind of java-script that you write, like we can get it executed on click of a button or link present on your detail page of a record. Below is the simple example and you can use it and modify it accordingly :

Javascript code:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 
try{ 
var query = "SELECT Id,Name from Account LIMIT 2"; 
var records = sforce.connection.query(query); 
var records1 = records.getArray('records'); 
alert(records); 
var accountNames = ''; 
for(var i=0;i<records1.length;i++){ 
accountNames = accountNames + records1[i].Name + ','; 
} 
alert(accountNames); 
if(records1.length == 1){ 
//window.location.href = 'http://www.google.com'; 
}
else{ 
alert('There is no Account'); 
} 
} 
catch(e){ 
alert('An Error has Occured. Error:' +e); 
}

you need to use .js files that are in first two lines in order to use the api of salesforce to connect and fetch the records using SOQL. In the example you will see result of SOQL in alert statement. The result that is returned contains a ‘records’ named array component that can be used to iterate over and go through all the records and use it in the same manner as we do in usual apex program. For ex account.id, account.Name etc.

You can also use merge fields to create dynamic queries.

Similarly you can use javascript to create, update or delete the salesforce object’s records using API. Below is the sample code you can use to create a new account record in your org.

Javascript code:

try{ 
var accounts = []; 
var account = new sforce.SObject("Account"); 
account.Name = "my new account Test"; 
accounts.push(account); 
var results = sforce.connection.create(accounts); 
if (results[0].getBoolean("success")) { 
alert("new account created with id " + results[0].id); 
} else { 
alert("failed to create account " + results[0]); 
} 
}
catch(e){ 
alert('An Error has Occured. Error:' +e); 
}

you just need to create a new button and fill the details as shown below in the screenshot:

SOQL in javascript example

Below this there would be a text box where you need to write your javascript code (provided above). After saving the button, you need to get it on your page layout and we are good to go.

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/soql-query-in-javascript-example/

Older posts «