sorting tables in visualforce

A List of records returned by select query can be sorted using order by clause. The field with which the resulting list be sorted should be specified after the order by clause.
We can specify whether we want a ascending sorting or a descending sorting. If the ascending or descending is not specified then the query sorts in ascending order of the specified field.
For ascending just use the keyword "'ASC" and for descending use the keyword "DESC"
example:
1. List<Contact> conList = [select id,name,email from contact order by name desc];
2. List<account> accList = [Select id,name,accountnumber from account order by name asc] is same as below 
3.List<account> accList = [Select id,name,accountnumber from account order by name]
Here's an example that sorts a table showing 5 account records. Button sorts the table depending on the field selected for sorting

Visualforce Page
Controller

action status in visualforce

Action status is used to display the status of AJAX request. Following is an example for action status:-
Visualforce Page

<apex:page controller="actionstatusDemoController">
 <apex:form >
   <apex:pageblock id="pgblck">
     <apex:actionStatus id="actstatus" >
        <apex:facet name="start" >
          <img src="/img/loading32.gif" />                    
        </apex:facet>
     </apex:actionStatus>
     <apex:commandButton value="Submit" status="actstatus" action="{!demomethod}" reRender="pgblck"/>
   </apex:pageblock>
 </apex:form>

</apex:page>

Controller

Public with sharing class actionstatusDemoController {
 Public actionstatusDemoController(){
 }

 Public void demomethod(){
 }

}

get current record id salesforce

May times we require the current record id in controller. For example if you 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 we can use ApexPages.CurrentPage().getparameters().get('id').
In the following example the custom button on account(overridden with following vf page) when clicked shows you the id of the record in visualforc apge.
Visualforce Page

<apex:page standardController="Account" extensions="SimpleDemoController">
  <apex:form >
    <apex:pageBlock >
        Id of the current record is : <b>{!recordId}</b>
    </apex:pageBlock>
  </apex:form>

</apex:page>
Id of the current record is : {!recordId}
Controller
Public with sharing class SimpleDemoController { 
Public string recordId {get;set;} 
Public SimpleDemoController(ApexPages.StandardController controller) { 
recordID = ApexPages.CurrentPage().getparameters().get('id'); 

}

If you want to get any other fields from that record you will have to query that record using the retrieved id as shown in the below example where some of the account fields are displayed.
Visualforce page

<apex:page standardController="Account" extensions="SimpleDemoController">
  <apex:form >
    <apex:pageBlock >
      Account Name : <apex:outputField value="{!accRec.Name}"/><br></br>
      Account No. :<apex:outputField value="{!accRec.Accountnumber}"/><br></br>
      Annual Revenue :<apex:outputField value="{!accRec.annualrevenue}"/>
    </apex:pageBlock>
  </apex:form>

</apex:page>
Account Name :
Account No. :
Annual Revenue :
Controller
Public with sharing class SimpleDemoController { 
Public account accRec {get;set;} 
Public SimpleDemoController(ApexPages.StandardController controller) { 
accRec = [select id,name,accountnumber, annualrevenue from account where id=:ApexPages.CurrentPage().getparameters().get('id')]; 
}

We can also get the current record id/record from the standardcontroller methods getid(), getrecord() as shown in the example below:
Public with sharing class SimpleDemoController { 
    Public account accRec {get;set;} 
    Public SimpleDemoController(ApexPages.StandardController controller) { 
          accRec = [select id,name,accountnumber,annualrevenue from account where id=:controller.getId()]; 
 }
}
getRecord() returns the record but to access the fields of that record; those fields should be referenced in the associated Visualforce markup or should be queried before showing in page.

Public with sharing class SimpleDemoController { 
Public account accRec {get;set;} 
Public SimpleDemoController(ApexPages.StandardController controller) { 
accRec =(account)controller.getRecord() ; 

}

select all checkbox using javascript in visualforce page

Javascript can be used to implement select all checkbox in a table column. Following example uses java script to build such column header.

Visualforce Page
Controller

List has no rows for assignment to SObject

This error " List has no rows for assignment to SObject" occurs if you try to put a value from list(that would return 1 record) into a defined variable(to accept a single value) and the list in reality does'nt return any value. This results in executing variablename =null;
Following example depicts the error " List has no rows for assignment to SObject".

Visualforce Page
Controller
In the statement,
conRec = [Select Name,id from contact where id=:'zzzzz' limit 1];
Query doesnt return any record which throws the exception " List has no rows for assignment to SObject".
We can put such kind of code in try and catch and show user a desired message.

show error message in visualforce page

Many times it is required to show warning,error or information messages on a visualforce page so as to indicate to the user. For these, salesforce provides page message,pagemessages,message and messages components.
We have to create a new instance of the message in apex and make sure we have placed the messages component on the visualforce page.
In the below example messages are displayed on button press if any of the input values are not submitted.
Visualforce Page
<apex:page extensions="ErrorDisplayDemoController" standardcontroller="Account">
 <apex:form>
   <apex:pageblock>
      <apex:pagemessages id="shwmsg"></apex:pagemessages>
         <apex:panelgrid columns="2">
           Account Name <apex:inputtext value="{!accountname}">
           Account Number <apex:inputtext value="{!accountnumber}">
           <apex:commandbutton action="{!UpdateAccount}" rerender="shwmsg" style="width: 70px;" value="Update">
         </apex:commandbutton></apex:inputtext></apex:inputtext></apex:panelgrid>
    </apex:pageblock>
 </apex:form>
</apex:page>
Controller
Public with sharing class ErrorDisplayDemoController { 
Public string accountname{get;set;} 
 Public string accountnumber{get;set;} 
 Public ErrorDisplayDemoController(ApexPages.StandardController controller) {
 } 

Public void UpdateAccount(){ 
     if(accountname == '' || accountname == null) 
         ApexPages.addmessage( new ApexPages.message(       ApexPages.severity.WARNING,'Please enter Account name')); if(accountnumber == '' || accountnumber == null) 
 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.error,'Please enter Account number')); 
 }
 }

list has more than 1 row for assignment to sobject

You will get this kind of error whenever you try to put value in a variable(that can store a single value of defined type) and the right hand side query returns more than one values.For example, you have a variable of type account and you equate it with a select query that returns more than one record.
In the following example you will see the error "List has more than 1 rows for assignment" when you press the button.


Visualforce page
Controller
In this line,
 account acc = [select id from account ];
Variable acc can accept a single record but query returns more than one record which throws the exception "List has more than 1 rows for assignment"
Had there been a limit parameter specified with value 1 or if the query had returned exactly one record the exception wouldn't have appeared.
  account acc = [select id from account limit 1]; or
  account acc = [select id,name from account where id=:'somerecordID']
We can also get the field value in a variable from a query provided the query returns only one record as below:
String AccName = [Select name,id,accountNumber from account limit 1].name;
Make sure the fields whose value is to stored in variable should be queried as above.

mass update visualforce component

A visualforce component for mass update of records.
Just pass the list of records to be updated and the fields to be displayed in table to the visualforce component. <c:massEditComponent inputsObjectList="{!accList }" InputFieldList="{!sObjectfieldList}"/>      


Visualforce componet. Name :massEditComponent
Visualforce component controller
An example that will call the above visualforce component is as below (You need to create a fieldset on whichever object you wish also create a list of records and pass it to component)
Visualforce page that call the above visualforce component
Visualforce controller for above vf page

visualforce page as pdf

We can deliver a visualforce page as pdf using renderAs attribute in page component of the visaulforce page. In the following example the page is rebdered as pdf that shows 10 account records in a table.

Visualforce page Controller

pass parameter to visualforce page

We can pass parameters to a visualforce page in pagerereference object using method :getParameters(). In the following example we are passing account record id to a visualforce page "callvfpage".

Visualforce page that calls another page and passes parameter as " account record id" Controller Visualforce that is being called and supplied with a account record id. Name of vf page -"callvfpage"

avoid recursive trigger salesforce

Recursion occurs when the code gets called again and again and goes into a infinite loop. It is always advisable to write a code that does not call itself. However, sometimes we are left with no choice. Recursion occurs in trigger if your trigger has a same DML statement and the same dml condition is used in trigger firing condition on the same object(on which trigger has been written)
For example, if your trigger fires on after update on contact and you update any contact record in your trigger then the same trigger will be called and will lead to a infinite loop.
To avoid this kind of recursion and call the trigger only once we can use global class static variable.
As an example let says you have following trigger on contact:
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'testemail@kmail.com';
 update conRec;
 }
}
As you can see the trigger is getting called on after update and as the trigger has a DML update statement on the same object, same trigger will be called again leading to recursion.
To avoid this, just create one global class with a static global boolean variable as below.
global Class recusrssionPreventController{
Global static boolean flag = true;
 Public recusrssionPreventController(){
 }
}
And set this boolean variable in your trigger and then set this boolean variable to false as done in the trigger below
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
if(recusrssivePreventController.flag == true){
   recusrssivePreventController.flag = false;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'testemail@kmail.com';
 update conRec;
 }
}
This will call the trigger only once and hence avoid recursion.

salesforce override related list button

For overriding a related list button we have to use standard list controller. The syntex used in defining this standard list controller is same as standard controller. That is, we need not write it as standardlistcontroller in page tag, but we have to use "recordSetVar"  attribute. This variable indicates that the standard controller is a list controller. Also this variable can be used to access the selected record in related list.
To use standard list controller define the page attribute as below (example on contact)
 
<apex:page standardController="Contact" recordSetVar="LisRecs" extensions="relatedListoverideController">
In the following example a "list button" created on contact is overridden with following visualforce page that shows the selected contact records in related list (example contact related list on a account record)
Visualforce page
Controller

inline edit visualforce

Sharing an example where inline editing has been used in Visualforce page. In the following example just click the checkbox to enable inline editing.

Visualforce page
Controller

test class for batch apex

Let us learn to write a test class that covers a batch apex class. Nothing better than learning from a working example.
Here is a test class for a batch apex class that updates account records that are passed through a select query.

Batch apex class

global class BatchProcessAccount implements Database.Batchable<sobject>{
    String query;
  
    global Database.querylocator start(Database.BatchableContext BC){
        Query = 'Select id,name,AccountNumber,type from account'; 
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<account> scope){
       List<account> AccountList = new List<account>();
       for(account acc : scope){
           acc.AccountNumber= '8888';
           AccountList.add(acc);
       }
       update AccountList ;
    }
  
    global void finish(Database.BatchableContext BC){
    }

}
Test class for above batch apex class

@isTest
  private class BatchProcessAccount_Test { 
    
static testMethod void BatchProcessAccount_TestMethod (){
     Profile prof = [select id from profile where name='system Administrator'];
     User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com');
                insert usr;
   Account accRec = new Account(name='testName', Ownerid = usr.id);
   insert accRec ;
   Test.StartTest();
   BatchProcessAccount objBatch = new BatchProcessAccount();
   ID batchprocessid = Database.executeBatch(objBatch);
   Test.StopTest();
  }

}


Just create a instance of the batch apex class: BatchProcessAccount objBatch = new BatchProcessAccount();
and then pass the craeted varaible in executebatch method as below:
   ID batchprocessid = Database.executeBatch(objBatch);

sosl salesforce example

SOSL is a select query that returns list of lists. That is, it can return list of multiple objects. It searches a parameter within fields fo multiple objects as specified in the query.
In the below example string 'test' is being searched in 4 objects Opportunity,account,Lead and contact. You need to specify in which fields it should search this string.
For example, if you want it to search in name and description fields of account then it would look like  account( name,description)
The list of lists has list of objects in the order mentioned in the query. For example if you specify account as first object in query; then the account list will be available at 0th location of list of lists.
visualforce page
<apex:page controller="DeferenceDemoController">
  <apex:form>
    <apex:commandbutton action="{!soslDemo_method}" value="Show records using SOSL">
    <apex:pageblock title="Accounts">
   <apex:pageblocktable value="{!accList }" var="acc">
  <apex:column value="{!acc.name}">
  <apex:column value="{!acc.Type}">
   </apex:column></apex:column></apex:pageblocktable>
    </apex:pageblock>

 <apex:pageblock title="Contacts">
<apex:pageblocktable value="{!conList}" var="con">
  <apex:column value="{!con.name}">
  <apex:column value="{!con.email}">
  </apex:column></apex:column>
</apex:pageblocktable>
 </apex:pageblock>

 <apex:pageblock title="Leads">
<apex:pageblocktable value="{!leaList}" var="lea">
  <apex:column value="{!lea.name}">
  <apex:column value="{!lea.company}">
   </apex:column></apex:column>
</apex:pageblocktable>
 </apex:pageblock>

 <apex:pageblock title="Opportunities">
<apex:pageblocktable value="{!optyList}" var="opty">
  <apex:column value="{!opty.name}">
<apex:column value="{!opty.StageName}">
</apex:column></apex:column>
</apex:pageblocktable>
 </apex:pageblock>
  </apex:commandbutton>
 </apex:form>
</apex:page>


Controller
Public with sharing class DeferenceDemoController { 
Public List optyList {get;set;} 
Public List leaList{get;set;} 
Public List conList{get;set;} 
Public List accList{get;set;} 

Public DeferenceDemoController(){ 


Public void soslDemo_method(){ 
optyList = New List(); 
leaList = New List(); 
conList = New List(); 
accList = New List(); 
List> searchList = [FIND 'test' IN ALL FIELDS RETURNING Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName),Lead(company,name,status) ]; 
accList = ((List)searchList[0]); 
conList = ((List)searchList[1]); optyList = ((List)searchList[2]); leaList = ((List)searchList[3]); 


}




As of now the SOSL can return only 2000 records (Combined for all the objects that are queried in the SOSL query) thsi is as per governer's limit.

actionpoller in salesforce

Action poller acts as a timer in visuaflorce page. It is used to send an AJAX request to the server depending on the time interval (time interval has to be specified or else it defaults to 60 seconds).
In the action attribute a controller method gets called. The method gets called with a frequency defined by the interval atribute which has to be greater than 5 seconds.
In the following example action poller calls the method "CounterMethod" every 5 seconds where the variable "seconds" counter is updated. Rerender attribute refreshes the page block hence showing the updated value of variable "seconds".

Visualforce page

Controller

Time out can also be specified as an attribute in action poller. Once the time out point is reached it stops making AJAX callout to the server and controller method is no more called.

record is read-only trigger

This post is regarding a error that we get because of trigger. "execution of AfterUpdate caused by: System.FinalException: Record is read-only"
This kind of error occurs if you try to update lists/record which are/is read only in the trigger execution. For example, trigger.new and trigger.old are both read only lists and cannot be applied with a DML operation.
Say if you write Update trigger.new; in your trigger you will get the above mentioned error.
A field value of object can be changed using trigger.new but only in case of before triggers. But in case of after triggers changing the values of the records in trigger.new context will throw exception as "Record is read only"
Example:

trigger mytrigger on account(before insert,before update){
  for(account ac:trigger.new){
      ac.name ='new name';
  }
}
Above code will update the names of the records present in trigger.new list. But, the below code will throw run time exception "Record is read only".
trigger mytrigger on account(after insert,after update){
  for(account ac:trigger.new){
      ac.name ='new name';
  }
}
Also trigger.old will always be read only no matter where you use it either before trigger or after trigger.
That is both the below codes will throw run time exception as trigger.old is read only
trigger mytrigger on account(after insert,after update){
  for(account ac:trigger.old){
      ac.name ='new name';
  }
}
trigger mytrigger on account(before insert,before update){
  for(account ac:trigger.old){
      ac.name ='new name';
  }
}
Let us briefly summarise on what we discussed above:
1. Trigger.new and trigger.old are read only
2. An object can change its own field values only in before trigger: trigger.new
3. In all cases other than mentioned in point 2; fields values cannot be changed in trigger.new and would cause run time exception "record is read only"

calling one visualforce page from another

This is regarding calling a visualforce page from another visualforce page.You may need to call a particular visualforce page after pressing a button or when certain criteria is met. We can call a visualforce page using pagereference object as done in the example below.

Here is a visualforce page that has a button "Call visualforce page". Upon pressing this button "Call a visualforce page", a different visualforce page is called.

  Visualforce page having button "Call visualforce Page"

Controller for above visaulforce page

Visualforce page that is called from above visualforce page
Page Name: DemovfPage

Here, in the method "Call_VF_Page" a instance of pagereference object is created wherein the name of the visualforce is passed.
PageReference openvfpage = New Pagereference('/apex'+'/DemovfPage');
Make sure that your return type is pagerefrence which will make sure new visualforce gets opened.

action support salesforce

Action support component adds AJAX support to another component, this allows the component to call a controller method when a particular event occurs(for example onlcik, onblur etc). It also allows to rerender,rendere page sections as desired.

In the following example a controller method is called when you click within a textbox using actionsuppot component.

Visualforce page

<apex:page controller="DemoController">
   <apex:form >
       <apex:pageBlock >
             Click Inside this block <apex:inputtext >
            <apex:actionSupport event="onclick" action="{!DemoMethod}" rerender="pgblck"/>
            </apex:inputtext>  
       </apex:pageBlock>
       <apex:pageblock id="pgblck">
             <apex:outputText value="{!outValueSecond }"/>
       </apex:pageblock>
   </apex:form>
</apex:page>

Controller

Public with sharing class DemoController {
Public String outValueSecond{get;set;}
Public String outvalue{get;set;}
Public boolean flag{get;set;}
  Public DemoController(){
     outvalue = 'Before Value';
     outValueSecond = 'before value set in constructor';
  }
   
  Public void DemoMethod(){
   outValueSecond = 'After value set in controller method. This method is called using action support added to inputtext compoennt';
  }
}

In this example initially the lower pageblock has a value that is set in constructor, but when the mouse is clicked in the text box the controller method is called which changes the value of the variable that is displayed in the lower pageblock. The controller is called by using action support for the inputtext. The action support also rerenders the lower page block which refreshes the lower block and hence shows the new value set in controller method.


















Action support for picklist in salesforce

One of the most common requirement that we come across, is building a picklist dependency in visualforce page. Wherein, we want to automatically set the dependent picklist based on controlling picklist field. For building such a functionality you can use action support as done in below example.

In this example, once the country is selected onchange of the picklist value action support get triggered and and it calls the method "capitalcal" which actually calculates the state value and then re renders the block that displays the state value calculated. Action support provides support for calling the controller class method on a ajax event and then also rerender the block or a section.

<apex:actionSupport> can be useful in building similar functionalities, you can also control other thing like images and rerender based on calculations done in a called class method. It helps in providing AJAX support to other visualforce components. Many time we have requirements where in we need to build dynamic picklists and also display values based on various calculations, at such time we can use actionsupport. Drop down values can be set using selectionoption and selectlist as done in below example. There are other attributes that can also be sued like status, timeout, rendered, etc.

Visualforce page

<apex:page controller="picklist_actionsupportcontroller" showHeader="true">
    <apex:form id="formId">
        <apex:pageBlock >
        <apex:pageBlockSection >
        <apex:selectList value="{!SelectedCountry}" size="1" >
            <apex:actionSupport event="onchange" action="{!capitalCal}" rerender="optxt"/>
            <apex:selectOptions value="{!Country}" />
        </apex:selectList>
        </apex:pageBlockSection> 
        <apex:pageblockSection >
        <apex:outputText id="optxt" value="{!CountryCapital}" label="Capital">           
        </apex:outputText>
        </apex:pageblockSection> 
        </apex:pageBlock>  
    </apex:form>
</apex:page>

Class

public with sharing class picklist_actionsupportcontroller {

 public SelectOption[] getCountry() {
        return new SelectOption[] { new SelectOption('-None-', '-None-'), 
            new SelectOption('India', 'India'), 
            new SelectOption('Japan', 'Japan'),
            new SelectOption('China', 'China')
        };
    }

    public String SelectedCountry{ get; set; }
    public string CountryCapital{get;set;}
    public PageReference capitalCal(){
        if(SelectedCountry == 'India')
        CountryCapital = 'Delhi';
        
        if(SelectedCountry == 'Japan')
        CountryCapital = 'Tokyo';
        
        if(SelectedCountry == 'China')
        CountryCapital = 'Beijing';
        
         
        if(SelectedCountry == 'New Zealand')
        CountryCapital = 'Auckland';
        return null;
    }

}

actionfunction and actionsupport in salesforce

i have already covered the difference between action function and action support in a separate post. <apex:actionFunction> is a visualforce component that provides support for calling a controller method directly from the visulaforce page java script. Where as, as disused above actionsupport provides support for other component in calling a controller method.

Action support vs action poller and action region

Action poller is a like a timer that can send ajax request on specified time intervals. Minimum time difference can be 5 sec. You can use action poller as counter, also make sure you don't overdo in a method that is being called using action poller and always keep it light with almost no dmls or query. The time interval with which you want to call the method should be specified in terms f second in a attribute "interval".


<apex:actionRegion> component is used to decide and segregate which component should be processes by server when an AJAX request is sent.