Use static resource in Visualforce

Use static resource in Visualforce – Salesforce

Force.com platform provides us a facility to upload, manage and use the content that is static (not changing) for your organization, and it can be stored under “Static Resources“. It can be a Javascript file, CSS file, an image or even a zip file containing all the files required in one zip file. Today we’ll see how to use static resource in Visualforce – Salesforce.

Use a static resource to display an image on a visualforce page

In example we will cover, how to use a static resource to display an image on a visualforce page.

Below are the ways to use the static resources in our visualforce pages:

Suppose there is a single file like any single image or standalone css file, that you need to refer in your VF page, then you can directly use the “$Resource.resourceName” to refer the static resource where ‘$Resource‘ is a global variable to use any static resource within visualforce page. You need not to hard code the path of the static resource in VF page code. Below are some examples of the same.

Suppose you have an image file uploaded in static resource with name “Z_test” as shown below in the screenshot.

Static resource

You can refer this image in your code using expression {$Resource.Z_Test}. Below are some other examples as well:


<!-- An image can be referenced like this -->
<img src="<strong>{!$Resource.Z_Test}</strong>"/>

<!-- Similarly any CSS file can be referenced like below -->
<apex:stylesheet value="<strong>{!$Resource.sampleCss}</strong>"/>

You need to remember only the keyword “$Resource” and the name of the static resource and not the name of actual file.

Similarly when we have the bundle of files, uploaded as a zip file in static resources section, then along with the name of static resource, you have to give the path to the file within the context of the archived zip.

Suppose below is the directory structure of the zip file with the name “bootstrap” that you have uploaded, in which you have three different folders for storing CSS, images, and JS files respectively.

Static resource archive structure
So, to reference a particular file at a given location, you need to give the path of the file in context of the zip, along with the name of static resource while referencing in Visualforce page code. For this we have to use a function called “URLFOR(nameOfStaticResource, RelativePathOfFile)”. Below code snippets shows you how to refer the particular files.


<meta charset="utf-8" />Force.com Developer<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- Static Resources for CSS -->
<apex:styleSheet value="{!URLFOR($Resource.bootstrap, 'bootstrap/css/bootstrap.css')}"/>
<apex:styleSheet value="{!URLFOR($Resource.bootstrap, 'bootstrap/css/bootstrap-responsive.css')}"/>

<!-- Static Resource for individual imag -->
<image src="{!URLFOR($Resource.bootstrap, 'img/glyphicons-halflings.png')}"/>

Above we explained the two ways of using the static resources in visualforce page, one for single file, another for the files within a zipped static resources file.

Hope this will help you in your coding.

Happy coding !! Good Luck 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/use-static-resource-in-visualforce/

apex:pageMessage and apex:pageMessages – Salesforce

apex:pageMessage and apex:pageMessages – Salesforce

Most of the times we are confused between these two visualforce components i.e. apex:pageMessage and apex:pageMessages. A small different of ‘s’. Let’s see the difference between apex:pageMessage and apex:pageMessages – Salesforce.

We are confused that which one should we use, and in which case. There is a small difference between these two. Let me explain the same:

We should use apex:pageMessage when we want to have individual message on the visualforce page and you provide the message to be displayed in the attributes of this tag. This is a kind of static message which you will write in visualforce itself, and can put some conditions in rendered attribute to display the message. The strength attribute of the tag controls the size of the message box displayed on the page. No need to have any controller code for adding the message on the page, because message has been written in visualforce page itself.


<apex:page controller="theController">
<apex:pageMessage severity="Error" summary="First Error message on page" strength="1"/>
<apex:pageMessage severity="Error" detail="Second Error message on page" strength="2"/>
</apex:page>

apex:pageMessage and apex:pageMessages - Salesforce

apex:pageMessage

This can be used to display any custom message that you always want to appear on the screen. There may be a case that whenever a user is on a form you may want a warning to appear to display important information to them.

You can also use this to conditionally display a message, based on some condition that you put in the rendered attribute of this component.

Now Let’s talk about apex:pageMessages:

apex:pageMessages is used to display more than one message on a visualforce page. It will display Salesforce generated messages(probably some exception or error) as well as custom messages that you have added to the ApexPages class in your controller code.

Below is the sample code. All the messages added in apex code using ApexPages class are shown in one box only unlike the previous tag apex:pageMessage where all the messages are shown in different boxes as they are put on page. Below is one example:

<apex:page controller="theController">
<apex:pageMessage severity="Error" summary="First Error message on page" strength="1"></apex:pageMessage>
<apex:pageMessage severity="Error" detail="Second Error message on page" strength="2"></apex:pageMessage>
<apex:pageMessages ></apex:pageMessages>

</apex:page>

The controller code for the same below:


public class theController {

public theController(){

ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'First Error Message added from apex'));
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Second Error Message added from apex'));

}
}

apex:pageMessage and apex:pageMessages - Salesforce

apex:pageMessages

Noticed that, how a single instance of the apex:pageMessages handles all of the errors on the page. The use case for this object is to capture all errors on the page including the error or exception messages generated by salesforce, and the messages added in ApexClass as well. It should be used on most custom Visualforce page as a catch all to let users know what errors occured (if no other messaging is used).

Best practice is to always keep apex:pageMessages on your page, because sometimes Salesforce generates some exception or error (may be because of some trigger or workflow), but because of non-availablitiy of this tag on your page, those messages are not displayed and you are confused why my page or functionality is not processing and not going further.

So I would suggest always keep apex:pageMessages tag on your visualforce page.

Good Luck !!

Permanent link to this article: https://www.sfdcpoint.com/salesforce/apexpagemessage-and-apexpagemessages-salesforce/

Relationship Query in Apex – Salesforce

Relationship Query in Apex – Salesforce

Relationship Query in Apex – Salesforce

soql relationship query

Most of the times, we have relationships between the objects(master-detail OR lookup) and often we need to fetch the list of all child records related to parent record in SOQL. This can be achieved using relationship query in Salesforce.

We can also say it as a Inner Query (query inside query).

For using relationship query, most important is, to know the Name of relationship between the two objects. You can get this relationship name by going to the Look-up OR Master-detail field on child object.

Parent to child query in salesforce using inner query

For parent-to-child relationships, the parent object has a name for the child relationship that is unique to the parent, the plural of the child object name. For example, Account has child relationships to Assets, Cases, and Contacts among other objects, and has a relationshipName for each, Assets, Cases, and Contacts.These relationships can be traversed only in the SELECT clause, using a nested SOQL query.

Here are two examples of parent to child query in salesforce

For Standard relation

First one is for Account(Parent) – Contact (Child) relationship. Below screen, we have opened the Lookup field present on contact(child object). We also call it soql relationship query. Here is the screen that you will see after clicking on the look-up/Master-detail field name that is present on child object.

Child Relationship name

 

For custom relation using __r in salesforce

The second one is for some custom object. When we create a custom relationship field on any object, we get an option to choose the name of relationship, while creating the look-up or Master-Detail relationship field. Below you can see the same, and then the same name is used in relationship queries.

How to create relationship name

Then this relationship name reflects on the custom field as shown below:

Child Relationship name - 2

 

So, in case of relationship between standard objects, relationship name is fixed already, and you can not change, but in case you are creating the relationship on your own, then you get the option of choosing the relationship name.

Now you have got the relationship name. We’ll see, how to construct the query required for our problem i.e. to get all the child records related to one parent record in a single query.

Here is a significant difference while making relationship queries for standard relationships(already defined by salesforce) and custom relationships(defined by user – b/w two custom objects OR b/w custom & standard object).

For example, for account and contacts relationship(already defined by salesforce), the query will be like:

List<Account> accList = [select id,name,(select name, id, email from contacts) from account];

Here you can see in the phrase (select name, id, email from contacts ), we have used the relationship name as it is mentioned on the field detail page as shown below:

Child Relationship name

But in case of custom relationship the query will be like:

List<Account> accList = [select id, (select id, name from tests__r) from account];

Here we have used __r with the relationship name. We have to use __r suffix after the relationship name shown on the field detail page as shown below:

Child Relationship name - 2

This relationship query returns all the accounts with all the child test records associated to each account record. You can use the query result as shown below:


//Perform the query on Account.
 
List<Account> accList = [select id, (select id, name from tests__r) from account];
 
//Iterate over the account with.
for(Account a : accList){
 
//For each account object, get the child records using tests__r and iterate over each child records.
for(test__c test : a.tests__r){
 
System.debug('The test name is:::::' + test.name);
 
}
 
}

Child to parent query in salesforce

For child-to-parent relationships, the relationship name to the parent is the name of the foreign key, and there is a relationshipName property that holds the reference to the parent object. For example, the Contact child object has a child-to-parent relationship to the Account object, so the value of relationshipName in Contact is Account. These relationships are traversed by specifying the parent using dot notation in the query, for example:

Contact c = [Select FirstName, LastName, Account.Name, Account.Industry from contact where LastName = ‘sfdcpoint’];

Limitation of Relationship Query

  • In each specified relationship, only one level of parent-to-child relationship can be specified in a query. For example, if the FROM clause specified Account, the SELECT clause could only specify the Contact or other objects at that level. It could not specify a child object of Contact.
  • No more than 20 relationships can be specified in a single query.
  • In each specified relationship, no more than five levels can be specified in a child-to-parent relationship. For example, Contact.Account.Owner.FirstName (three levels).

 

For more details please refer official link

Good Luck !! 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/relationship-query-apex-salesforce/

Transient Keyword – View State – Visualforce – Salesforce

Transient Keyword – View State – Visualforce – Salesforce

View State in salesforce

What is view state in salesforce?

ViewState holds state of the visualforce page that holds state that includes the fields, components and controller state. Viewstate data in encrypted and cannot be viewed tools like firebug. There is a limit of 135KB of view state.

To maintain state in a Visualforce page, the Force.com platform includes the state of components, field values, and controller state in a hidden form element. This encrypted string is referred to as the view state and has a limit of 135KB.

We can check view state from developer console or from visaulforce page in development mode by enabling setting in Advanced user details:

View State In Salesforce

How to reduce view state in Salesforce

Transient Keyword – View State – Visualforce – Salesforce: We can use transient keyword with apex class’s instance variables when we want that values of those variables should not be transferred as part of the view state of visualforce page. This helps us reducing the view state of visualforce page. As we all know that, there is a limit of 135KB of view state and many times this “Transient” keyword helps us to reduce the view state.

There are certain points that we should consider while using the transient keyword:

  1. The value of transient variable is only transferred from controller to visualforce page but not as part of view state. As the value is not part of view state, the changed value of that variable is not transferred back from visualforce page to controller when a new request is made by clicking a button or link.
  2. We should use the transient keyword mostly in case where we have read only Visualforce page and data doesn’t need to be sent back to controller in further requests. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page’s view state and would use too many system resources to be recomputed many times during a request.

Here is a very common and excellent example to help understand the concept of transient variable:

Visualforce page:


<apex:page controller="ExampleController">
Time1: {!t1} <br/><br/>
Time-Transient: {!t2} <br/><br/>
<apex:form >
<apex:commandLink value="Refresh"/>
</apex:form>
</apex:page>

Below is the controller for the same, where we have transient variable declared:


public class ExampleController {

DateTime t1;
transient DateTime t2; //declare

public String getT1() {
if (t1 == null)
 t1 = System.now();

return '' + t1;
}

public String getT2() {
if (t2 == null)
 t2 = System.now();

return '' + t2;
}
}

Click for Demo

In the above example and demo, you can see that clicking the refresh button on the page causes the transient date T2 to be updated every time, because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been de-serialized from the view state, so it remains the same.

Going into more details, we can understand it like, when user made first request that means; when this page was accessed first time, at that time both the values were null, and getter method of both the variables checked for null and assigned the value of “System.now()” to the variables and values got displayed on visualforce page. But When visualforce was displayed for the first time, in the view state, there was only the value of non-transient variable which is T1 and not the transient one T2.

So, when user clicks on refresh, a new request is made. The getter methods again tries to check for null. Because the view state has the value of non-transient variable available, the value is taken from view state and as it is not null, system does not refresh the value with latest “System.now()” value.

BUT, for transient variable, since the view state does not hold the previous value, the getter method could not find any value and considering it null again, the getter method assigns the latest value of “System.now()” to the variable. That is why the value of transient variable gets refreshed.

Understanding the above example can give you a fair idea of where and why to use the transient keyword.

So, if you want the value of your variable on visualforce page only once, don’t need the value in further requests to controller, then use transient keyword, to make your page lighter with less size of view state.

Good Luck !! 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/transient-keyword-view-state-visualforce/

Test class in salesforce with example

Test class in Salesforce with example

Test class in salesforce

Testing is an important part of SDLC. So, before deploying our code to production environment, Salesforce requires at least 75% of your code to be covered by our test classes whic. Salesforce has done that to make sure that our code doesn’t break in any situation in Production. Today we’ll see how we write the test class with example in Salesforce.

Some points regarding the test classes in Salesforce, which you have to know for sure:

  1. At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. But this should not be our focus. We should aim for 100% code coverage, which ensures that you cover each positive and negative use case of your code to cover and test each and every branch of your code.
  2. Calls to System.debug are not counted as part of Apex code coverage.
  3. Test methods and test classes are not counted as part of Apex code limit. So, no worries about writing long test class with more methods just to make sure that all your code branches are covered.
  4. Every trigger you are trying to deploy should have at least 1% coverage, but yes overall coverage of your production org after getting your code deployed should be 75%, otherwise Salesforce won’t let you deploy your code.
  5. Class can be deployed on 0% coverage as well, but as I told in last point, that overall coverage of your production org after getting your code deployed should be 75%, otherwise Salesforce won’t let you deploy your code.

In the example below, we will learn how to write a very simple test class:

Apex Trigger:


trigger HelloWorldTrigger on Book__c (before insert) {
  Book__c[] books = Trigger.new;
  MyHelloWorld.applyDiscount(books);
}

Trigger Helper Class:


public class MyHelloWorld {
 public static void applyDiscount(Book__c[] books) {
   for (Book__c b :books){
     b.Price__c *= 0.9;
   }
 }
}

Test Class Code:


@isTest
private class HelloWorldTestClass {
 static testMethod void validateHelloWorld() {
 Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
 System.debug('Price before inserting new book: ' + b.Price__c);

 Test.startTest();
 // Insert book
 insert b;

 Test.stopTest();

 // Retrieve the new book
 b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
 System.debug('Price after trigger fired: ' + b.Price__c);

 // Test that the trigger correctly updated the price
 System.assertEquals(90, b.Price__c);
 }
}

The key points while writing a test class are:

  1. You have to start your class with @isTest annotation, then only Salesforce will consider this class as test class.
  2. Keep your class as Private, and the best practice is to name your test class as your original Class or trigger Name + ‘Test’.
  3. Methods of your test class have to be static, void and testMethod keyword has to be used.
  4. Prepare your test data which needs to be existing before your actual test runs. There are multiple techniques of creating test data now a days, for example, setup method, static resources etc. For more details about @testsetup method check below link @testSetup method in apex test class
  5. Use Test.startTest() and Test.stopTest() to make sure that the actual testing of your code happens with the fresh set of governer limits. These methods help you to reset your governor limits just before your actual code of testing get executed.
  6. Once your test code runs between Test.startTest() and Test.stopTest(), you must use assert statements to test whether your actual code is executing correctly and giving the results as expected. In our case, we are test whether book’s price has been set to 90 or not. If this assert statement returns false, then your test class will fail, and will let you know, that something is not correct in your code, and you need to fix your original code.
  7. Because we are testing a simple trigger, we could not show the testing using negative use cases, but in an ideal world, you should write multiple methods in your test class, few should test your positive use cases, and other should test your negative test cases.

Test class trailhead

Create test class

Good luck with your test classes!! 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/test-class-with-example-salesforce/

SObject row was retrieved via SOQL without querying the requested field

SObject row was retrieved via SOQL without querying the requested field

SObject row was retrieved via SOQL without querying the requested field is very common error in apex. As name of error suggest, this error occurs when we try to use some field of an object instance which is not queried.

There can be two possible reason for this error.

  1. When we try to use a field in Apex or visualforce which is not queried. For example:

    List accList = [SELECT Id, Name FROM Account WHERE Name like ='%test'];
    for(Account acc : accList){
    System.debug('Account industry is'+ acc.Industry);
    }
    

    Or if we try to use it in visualforce page like this

    <apex:outputField value="{!acc.Industry}"/>
    

Solution for this type of problem is very easy we can simply add Industry field in SOQL query like this:

List accList = [SELECT Id, Name FROM Account WHERE Name like =’%test’];

But sometime our visualforce page or apex class is very complex and we don’t know which field will be used.  In SOQL there is no standard way of querying all fields of object. In that case we can query all fields from SOQL using dynamic query.  For details refer to below link:

Dynamic SOQL query to fetch all fields in Salesforce

2.  The error “SObject row was retrieved via SOQL without querying the requested field” can occur when accessing a Visualforce page with a standard controller and a custom controller extension.

When a standard controller queries an object for a Visualforce page, it only retrieves the fields from the object that are referenced in the page.
This improves efficiency by not retrieving fields that are not needed by the Visualforce page.

When a custom controller references a field that is not included in the page, the field data is not available, and the error occurs.

Workaround:

  • You can add a SOQL query to the custom controller that queries the missing fields
  • You can add a hidden reference to the field in the Visualforce page.
For example:
<apex:outputText value="{!Condition__c.Criterion__c}" rendered="false"/>

Official Salesforce link

Happy Coding 🙂

 

Permanent link to this article: https://www.sfdcpoint.com/salesforce/sobject-row-was-retrieved-via-soql-without-querying-the-requested-field/

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: https://www.sfdcpoint.com/salesforce/pagination-using-standard-set-controller-salesforce/

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.

Continue reading

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

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: https://www.sfdcpoint.com/salesforce/get-current-record-id-salesforce/

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