Fieldset apex code salesforce

Fieldset apex code salesforce

Fieldset apex code salesforce

A field set is a grouping of fields for same object. We can use dynamic bindings to display field sets on our Visualforce pages. Fieldset is very useful when we are working with managed package.

If we are using standard controller, then using fieldset in visualforce is straight forward. You can view my previous post for using fieldset in visualforce pages.

But if we are using custom controller or extension, then we may need to query fieldset fields in SOQL query. So we will use dynamic SOQL query for querying all fields of fieldset.

By using dynamic SOQL query in Apex and using fielset in visualforce and Apex code. Our code will become dynamic, then we can add, remover or reorder fields in fieldset. By doing so, our code will become dynamic. There is no need to modify code when we will do any change in fieldset.

In the example below, we will use fieldset to display account list on visualforce page. We will use dynamic SOQL query in Apex code.

Click for Demo

First we need to create a fieldset. Go to Setup > Customize > Accounts > Field Set
Click on new. Enter all mandatory fields. Also drag and drop all required fields in fieldset.

Create account field set

Visualforce Page:

<apex:page controller="AccountFieldSetController" tabStyle="Account">
  <apex:form >
      <apex:pageblock >        
          <apex:pageBlockSection title="Account list" collapsible="false">
             <apex:pageBlockTable value="{!accList}" var="acc">
                 <apex:repeat value="{!$ObjectType.Account.fieldsets.accountFieldSet}" var="fieldValue">
                     <apex:column value="{!acc[fieldValue]}">
                     </apex:column>
                 </apex:repeat>
             </apex:pageBlockTable>
          </apex:pageBlockSection>
          
          <apex:pageBlockSection title="Account Dynamic query" collapsible="false">
              <apex:outputText value="Query is: {!queryString}" />
          </apex:pageBlockSection>
          
      </apex:pageblock>
    </apex:form>
</apex:page>

Apex Code:

public class AccountFieldSetController {
    public String queryString{get;set;}
    public List<Account> accList{get;set;}
    public AccountFieldSetController(){
        queryString = 'select id';
        for(Schema.FieldSetMember fld :SObjectType.Account.FieldSets.accountFieldSet.getFields()) {
         queryString += ', ' + fld.getFieldPath();
        }
        queryString += ' from Account limit 5';
        
        acclist = Database.query(queryString);
    }
    
}

We will get following output in visualforce page:

FieldSet Apex Code Salesforce Example

FieldSet Apex Code Salesforce

For more details about using fieldset in visualforce, refer to Fieldset visualforce page salesforce.

For more details about fieldset refer this official link.

 

Permanent link to this article: https://www.sfdcpoint.com/salesforce/fieldset-apex-code-salesforce/

Fieldset visualforce page salesforce

Fieldset visualforce page salesforce

Fieldset visualforce page salesforce

How to use fieldset in Salesforce Visualforce pages?

Fieldset:

A field set is a grouping of fields for same object. We can use dynamic bindings to display field sets on our Visualforce pages. Fieldset is very useful when we are working with managed package.

Field sets can be directly referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets.

A fieldset is a grouping of fields. For example, fieldset can contain fields like first name, last name, mobile, phone of user object. Consider a scenario, suppose we want to display some fields in a page and we want to keep the flexibility to change which fields are displayed. In such a scenario we should use field sets to add or remove the fields as per requirement.Which ever fields are included in the field set will be displayed in page. For this we will need to create a field set on object we wish, then we can access it directly in visualforce page.

Another scenario is, suppose visualforce code is part of managed package. In that case we can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code.

In the example below, we will display one fieldset for account object then we will display fieldset fields on visualforce page.

Click for Demo

Steps to create field set on an object :

First we need to create a fieldset. Go to Setup > Customize > Accounts > Field Set
Click on new. Enter all mandatory fields. Also drag and drop all required fields in fieldset.

Create account field set

Now we will create visualforce code which will use fieldset.
Visualforce Code:

<apex:page standardController="Account">
  <apex:form >
      <apex:pageblock >    
          <apex:pageBlockSection title="Account detail">
             <apex:repeat value="{!$ObjectType.Account.fieldsets.accountFieldSet}" var="fieldValue">
                 <apex:Inputfield value="{!Account[fieldValue]}"/>
             </apex:repeat>
          </apex:pageBlockSection>
      </apex:pageblock>
    </apex:form>
</apex:page>

We can add, remove, or reorder fields in a fieldset to modify the fields presented on the Visualforce page without modifying visualforce page code.

We will get following output in visualforce page:

fieldset Visualforce page

For more details about using fieldset in apex, refer to Fieldset apex code salesforce

Also for more details about fieldset refer this official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/fieldset-visualforce-page-salesforce/

Custom setting in Salesforce

Custom Setting in Salesforce

Custom setting in Salesforce are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database.

We can create custom setting in salesforce for storing data similar to custom objects in salesforce but here the data is static.

Similar to custom object, we can create fields in custom setting and after creating the fields, we can click on ‘Manage’ button to add records in that custom setting. Then we can use the values in these records in our apex code, validation rules. The benefit of using custom setting instead of custom objects:

  • Data in custom setting is available in application cache, hence efficient and fast access.
  • No need to waste SOQL for fetching data from custom setting. There are some methods available in custom settings that we can use to get the data instead of SOQL.

Types of custom settings available in salesforce :

List Custom Settings:

A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. Because the data is cached, access is low-cost and efficient: you don’t have to use SOQL queries that count against your governor limits.

Custom setting in Salesforce List

Hierarchy Custom Settings:

A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.

Custom setting in Salesforce Hierarchy

In above screenshot, you can see that records in a particular custom setting can be created for particular profile or user. But this is not the case with List custom setting. Records in list custom setting are available for all users and profile in application.

Salesforce imposes certain limits on the amount of cached data and on custom settings:

  • The total amount of cached data allowed for your organization is the lesser of these two values:
    • 10 MB
    • 1 MB multiplied by the number of full-featured user licenses in your organization

For example, if your organization has three full licenses, you have 3 MB of custom setting storage. If your organization has 20 full licenses, you have 10 MB of storage.

Each Certified managed package gets its own separate limit in addition to your organization limit. For example, if your organization has two certified managed packages installed and your organization has three full licenses, each certified managed package can have 3 MB of custom setting storage, in addition to your organization’s 3 MB custom setting storage limit.

  • 300 fields per custom setting.
  • You can’t share a custom setting object or record.
  • No owner is assigned when a custom setting is created, so the owner can’t be changed.
  • Custom settings are a type of custom object. Each custom setting counts against the total number of custom objects available for your organization.

For more details, please refer below link:

Official Link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-setting-salesforce/

Gets Maps from SOQL Query salesforce

Gets Maps from SOQL Query salesforce

As we all know, Apex code has limitation of  Number of code statements that can be executed. While writing Apex code, we should take care of number of code statement that are  executed to avoid governor limits. It is useful to understand how to reduce the number of executed code statements so that we can stay within the governor limits.

Normally we get list of records in a SOQL query.Sometime we also need set of id’s or map of record id’s and record or list of record id’s.

Apes code for above requirement will be as below:

//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>();

//Fetching all accounts
List<account> accList = [select Id,name,site,rating,AccountNumber from account limit 50000] ;

//Fetching Account ids
for(Account acc : accList){
	accIdsSet.add(acc.id);
	accIdsList.add(acc.id);
	accountIdObjMap.put(acc.id,acc);
}

In the code above, if there are large number of records(say 50000) then for loop will be executed 50000  times and also every line in for loop will be executed 50000 times. We can avoid this unnecessary for loop by using good SOQL query which will return map instead of list. After that we can easily get list of accounts or set of account Id’s or List of account Id’s using methods.

New Apex Code will be as below:

//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Fetching all accounts
List<account> accList = new List<Account>();

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>([select Id,name,site,rating,AccountNumber from account limit 50000]);

//getting list of account using map.values method
accList = accountIdObjMap.values();

//getting set of account Id's using map.keySet method
accIdsSet = accountIdObjMap.keySet();

//getting list of account Id's using list.addAll method
accIdsList.addAll(accIdsSet);

Permanent link to this article: https://www.sfdcpoint.com/salesforce/gets-maps-soql-queries-salesforce/

External Key in Salesforce

External Key in Salesforce

External Key is a very interesting and important feature given by Salesforce. It is very much helpful when we are importing some data from legacy system, means suppose the data in the old system needs to be migrated to salesforce and we want to avoid importing any duplicate records from that system into salesforce.

Then, how salesforce will come to know that on which basis, it should differentiate between the records being imported from external system.

For this purpose, we can define some field from legacy data that will act as unique identifier in salesforce and we can map that field with a custom field in salesforce that has attribute External Id true. So, whenever we will import data from legacy system, salesforce won’t allow any duplicate record based on the external id defined for that object.

We can define 3 external Ids for every object, and only three data types are allowed to be used in external id. These are (Email, text, number).

So, for example there are some records existing in external system. Please see the screenshot below:

External Id

Suppose these are records in external system and needs to be imported in salesforce and you want that duplicate records should not be imported in salesforce. So, we need to define some field on basis of which salesforce can decide which record is duplicate and which is not. So, in above screenshot we have picked Type to be an external id. Hence, salesforce won’t allow all the records highlighted in black border in the snapshot above because it will categorize them as duplicate record because one record with that particular Type value has already been imported(highlighted in red).

That is the importance of external Id while integrating with external systems. If you are working with external system, external id will become your best friend.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/external-key-salesforce/

Visualforce page render as pdf example

Visualforce page render as pdf example

We can render any page as pdf  by adding renderAs attribute to <apex:page> and specifying “pdf” as value. renderAs value is name of any supported content converter. Currently PDF is the only supported content converter. Setting renderAs attribute to “pdf” renders the page as a PDF.

Rendering a Visualforce page as a PDF is intended for pages that are designed and optimized for print. Standard components that are not  easily formatted for print or contain form elements like inputs, buttons, any component that requires Javascript to be formatted, should not be used.  We should always verify the format of your rendered page before deploying it.

Sometimes PDF fails to display all the characters properly. In that case we should adjust the fonts in our CSS to use a font that supports our needs. We can use style element for displaying content properly in PDF.

In the example below, we are showing 10 account in table in visualforce page which is renderAs “pdf”. We are just adding renderAs attribute in apex:page and giving “pdf” as its value.

Click for Demo

Visualforce Page

<apex:page controller="PdfExampleController" renderAs="pdf">
  <apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable value="{!accList}" var="acc" border="2">
           <apex:column value="{!acc.name}"/>
           <apex:column value="{!acc.annualrevenue}"/>
           <apex:column value="{!acc.type}"/>
           <apex:column value="{!acc.accountnumber}"/>
           <apex:column value="{!acc.rating}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
  </apex:form>
</apex:page>

Apex Code:

public with sharing class PdfExampleController {
    public List accList{get;set;}
    public PdfExampleController (){
        accList = [select id,name,type,accountnumber,annualrevenue,Rating from account limit 10];
    }
}

Please note that this page is not optimized to be renderAs pdf. Salesforce has provided Best Practices for Rendering PDFs.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/visualforce-page-render-pdf/

Salesforce record id hack first 3 digit

Salesforce record id hack first 3 digit

This post is going to be interesting. As we all know that each record in salesforce is identified by record id which is unique for every organisation. Salesforce record id can be 15 digit case sensitive or 18 digit case insensitive. Last three digits of 18 digit record id provide checksum of first 15 digits.

Now interesting and important point is that first 3 digits of record id determines SObject type of record. For every salesforce object first 3 digit of record id is unique. And for all standard salesforce objects, first 3 digits of record id is constant. For example, for standard Account object first 3 digit of record id is 001. Similarly for Contact object first 3 digit is 003. These first three digit of record id is known as ‘Record id prefix’.

For each custom object also, first 3 digit of record id is unique.

Trick 1:
Remembering these 3 digits of object’s record id is very useful. When we will enter first 3 digits of record id after instance URL we will be on List view page for that particular object.

Account List View

Trick 2:

We can also directly go to any object tab if we remember first 3 digit of object’s record id. For example, as we know first 3 digits of Account object’s record id is 001. So if we will enter ‘001/o ‘ after instance URL, we will land to Account tab. In similar way we can go to any tab if we know or remember first 3 digits of record id.

Account Tab

Permanent link to this article: https://www.sfdcpoint.com/salesforce/salesforce-record-id-hack-first-3-digits/

actionRegion visualforce salesforce

actionRegion visualforce salesforce

actionRegion provides an area of a Visualforce page that decides and separates which components should be processed by the force.com server when an AJAX request is generated. Only the components which are inside actionregion component are processed by server, so it increases visualforce page performance. Here components means, all visualforce tags like inputField, outputField, outputPanels etc.

actionregion is one of the most important tag which helps in increasing page performance. So we should try to make maximum use of actionregion in visualforce page. actionRegion component only defines which components the server processes during a request, it does not define which of the page are re-rendered when the request completes. We will still use reRender attribute on action component to decide area which should be rerendered AJAX request completes.

One more important point to note is that even when we use <apex:actionRegion> component, whole form is still submitted but only area which is inside actionRegion is processed by server.

I will explain importance of actionRegion with help of two examples. First example will not use actionRegion and second example will use actionRegion. Here in both example we are trying to show phone textbox, when we are selecting customer priority as high.

Example 1 Without <apex:actionRegion>

Click for demo without actionRegion

Without actionRegion Demo

In this example, we are trying to show phone textbox when we are selecting high customer priority, then we are getting error as SLA and Account name is required. So validation fails.

Visualforce Page:

<apex:page controller="withoutActionregionController" tabStyle="Account">
    <apex:form id="myform">
        <apex:pageBlock id="pageId">
            <apex:pageBlockSection title="If you will select High Customer Priority then phone textbox will be shown" columns="1" id="out" collapsible="false">
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="{!$ObjectType.Account.fields.CustomerPriority__c.label}" for="priority"/>
                    
                    <apex:inputField value="{!acc.CustomerPriority__c}" id="priority" >
                        <apex:actionSupport action="{!priorityChanged}" reRender="pageId" event="onchange"/>
                    </apex:inputField>
                </apex:pageBlockSectionItem>
                
                <apex:inputField value="{!acc.Phone}" rendered="{!showPhone}"/>
            </apex:pageBlockSection>  
            
            <apex:pageBlockSection title="Other Account Details" columns="2" collapsible="false">
                <apex:inputField value="{!acc.SLA__c}" required="true"/>
                <apex:inputField value="{!acc.Rating}"/>
                <apex:inputField value="{!acc.name}"/>
            </apex:pageBlockSection>  
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class withoutActionregionController {
    public Account acc{get;set;}
    public Boolean showPhone{get;set;}
    
    public withoutActionregionController(){
        acc = new Account();
        showPhone = false;
    }
    
    public PageReference priorityChanged(){
        if(acc.CustomerPriority__c == 'High'){
            showPhone = true;
        }
        else{
            showPhone = false;
        }
        return null;
    }
}

Now in second example we will use same code but with actionRegion tag. So in second example no validation error will be returned as only code inside actionregion component is processed by server.

Example 2 with <apex:actionRegion>

Click for demo with ActionRegion

with actionRegion Demo

Visualforce Page:

<apex:page controller="withActionregionController" tabStyle="Account">
    <apex:form id="myform">
        <apex:pageBlock id="pageId">
            <apex:pageBlockSection title="If you will select High Customer Priority then phone textbox will be shown" columns="1" id="out" collapsible="false">
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="{!$ObjectType.Account.fields.CustomerPriority__c.label}" for="priority"/>
                    
                    <apex:actionRegion >
                    <apex:inputField value="{!acc.CustomerPriority__c}" id="priority" >
                        <apex:actionSupport action="{!priorityChanged}" reRender="pageId" event="onchange"/>
                    </apex:inputField>
                    </apex:actionRegion>
                </apex:pageBlockSectionItem>
                
                <apex:inputField value="{!acc.Phone}" rendered="{!showPhone}"/>
            </apex:pageBlockSection>  
            
            <apex:pageBlockSection title="Other Account Details" columns="2" collapsible="false">
                <apex:inputField value="{!acc.SLA__c}" required="true"/>
                <apex:inputField value="{!acc.Rating}"/>
                <apex:inputField value="{!acc.name}"/>
            </apex:pageBlockSection>  
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class withActionregionController {
    public Account acc{get;set;}
    public Boolean showPhone{get;set;}
    
    public withActionregionController(){
        acc = new Account();
        showPhone = false;
    }
    
    public PageReference priorityChanged(){
        if(acc.CustomerPriority__c == 'High'){
            showPhone = true;
        }
        else{
            showPhone = false;
        }
        return null;
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/actionregion-visualforce-salesforce/

Difference between Export & Export All in Data Loader

Difference between Export & Export All in data loader is really interesting.

I was asked this question in one of my job interview.

Export and Export All

Export and Export All

There are two buttons available in dataloader ‘Export’ & ‘Export All’. Difference in both button functionality is very small. When we use ‘Export’ button for any object in salesforce, all records( excluding records present in Recycle Bin) present in the system for that particular object are exported to a .csv file. But when we use Export All, all records (including records present in Recycle Bin) for that particular object are exported to a .csv file. Deleted records present in recycle bin are also called ‘soft Deleted’ records.

When you choose fields to be extracted using data loader, you can select IsDeleted field as well because it tells which record is soft deleted and which is not.

IsDeleted

IsDeleted

(IsDeleted = true) –> record has been soft deleted.

(IsDeleted = false) –> record has not been deleted.

I clicked on Export All and in the screenshot below, you can see there are some records for which IsDeleted is true. These are some records that were present in recycle bin(soft deleted).

IsDeleted

For more reference on data loader, Go to Data Loader Reference

Permanent link to this article: https://www.sfdcpoint.com/salesforce/difference-export-export-data-loader/

actionPoller visualforce salesforce

actionPoller visualforce salesforce

Actionpoller acts as a timer in visuaflorce page. It is used to send an AJAX request to the server depending on the timeinterval that we specify in interval attribute (time interval has to be specified or else it defaults to 60 seconds).Each request can result in a full or partial page update.

<apex:actionPoller> has following important attributes:

  • interval: The time interval between AJAX update requests, in seconds. This value must be 5 seconds or greater, and if not specified, defaults to 60 seconds
  • action: The action method invoked by the periodic AJAX update request from the component.
  • reRender: Comma separated id’s of one or more components that are refreshed when request completes.

In the example below, action poller calls the method “callMethod” every 10 seconds. In callMethod, the variable “seconds” counter is incremented by 10. Rerender attribute refreshes the outputText, so seconds value in page will be refreshed.

Click for Demo

Visualforce Code:

<apex:page controller="actionpollerDemoController" tabStyle="Account">
    <apex:form >
        <apex:pageBlock id="myPageId">
            <apex:pageBlockSection title="actionPoller example" collapsible="false" columns="1">
              <apex:actionPoller action="{!callMethod}" reRender="out" interval="10"/>
              <apex:outputText value="{!seconds}" label="Time in seconds since action poller is called:" id="out"/>
            </apex:pageBlockSection>
         </apex:pageBlock>
      </apex:form>
</apex:page>

Apex Code:

public class actionpollerDemoController {
public  Integer seconds{get;set;}
  public actionpollerDemoController(){
   seconds = 0;
  }

  public void callMethod(){
    seconds = seconds + 10;
  }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/actionpoller-visualforce-salesforce/