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() ; 

}

5 comments: