Monday 6 February 2017

Display Helptext In Visualforce Page In Less Time, Check this out

Display Helptext In Visualforce Page In Less Time, Check this out

Whenever we override our salesforce standard page with custom page i.e. by visual force page, there is always be clients/Users many time demand for same Standard page layout inline Help Text bubbles.

The help text that is displayed next to this field as a hover-based tool tip, similar to the text that is displayed next to standard Salesforce fields if custom help is defined for the field in Setup.


Syntax to display Help Text:

{!$ObjectType.objectName__c.Fields.fieldName__c.inlineHelpText}

Create Visual force page: Copy and paste below sample code and click on Save button

<apex:page standardController="Account">
  <apex:pageBlock >
    <apex:form >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem helpText="{!$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText}">
                <apex:outputLabel value="{!$ObjectType.Account.Fields.LightingNitish__Account_Address__c.Label}" />
                <apex:inputField value="{!Account.LightingNitish__Account_Address__c}" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:form>
  </apex:pageBlock>
</apex:page>


Click on Preview button of visualforce page
Or 
You can Go to the URL and type (Change the yoursalesforceinstance with your salesforce org URL) and add any account valid record id.


https://yoursalesforceinstance.com/apex/VisualForcePageName.

Output:



Note: If you use "showHeader=false" in <apex:Page> then helpText is not displayed.

Here in above code you might confuse about field LightingNitish__Account_Address__c. 
LightingNitish__Account_Address__c is a combination of namespace and API name.
LightingNitish is my org namespace and then Account_Address__c custom field API name.

Other way to help text in Visual force page:



1. <apex:inputField> and <apex:outputField> shows help Text bubble when nested within a <apex:pageBlockSection> component automatically.
but in order to do this, you need to include a <apex:PageBlockSection> nested in a <apex:PageBlock>tag as well.

However, there are two scenarios where helpText Bubble is not displayed in the VisualForce page.

  1. If we use "Label" attribute of <apex:outputField> , then helpText bubble is not displayed in visualforce page.
  2. If we set "showHeader=false"  of <apex:Page>, in that case also helpText bubbles is not displayed in visualforce page.
Here I came up with my own idea to display help text at VF page with above two scenarios:


<div id="mainAccountContent">

    Sample help Text Example

    <span class="CustomHelpTextExample">

<img src="/HelpTextExample.gif" alt="Help" class="helpIcon" title="$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText"/>

    </span>
</div>

By Providing "$ObjectType.Account.Fields.LightingNitish__Account_Address__c.InlineHelpText" in TITLE attribute of <img> tag.
The helpText will be displayed as ToolTip Text.

You do not need to use <apex:PageBlockSection> tag.

Also in above code I used field LightingNitish__Account_Address__c. 
LightingNitish__Account_Address__c is a combination of namespace and API name. LightingNitish is my org namespace and then Account_Address__c custom field API name.

2. Use the <apex:pageBlockSectionItem> with attribute helpText filled. 
You can then "override" it or better say use you own custom help text independent of another one from the custom field:

<apex:pageBlock>
    <apex:pageBlockSection>
        <apex:pageBlockSectionItem helpText="Your custom help text.">
            <apex:outputLabel value="Account Name"/>
            <apex:inputText value="{!Account.Name}" />
        </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
</apex:pageBlock>

It looks like this then:


3. Display help text entered in the custom field under "Help Text". This text appears if you use a pageBlock together with an outputField:

<apex:pageBlock>
    <apex:pageBlockSection>
        <apex:outputField value="{!Account.Account_Address__c }" />
    </apex:pageBlockSection>
</apex:pageBlock>

Run Schedule a Class In Every 5 Mins in Salesforce

Run Schedule a Class In Every 5 Mins in Salesforce

By default you can run apex job every 1 hour using CRON expression but you can schedule this job 12 times at 5 min duration.

If you are not aware of Schedulable Batch Apex then first look Schedulable Batch Apex In 3 Easy steps In Salesforce

Then how to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.

Yes I have solution for it. So here is a small code to do so for every 5 minutes.

Example, you have Scheduler class namely ScheduleBatchApexClassExample and want to run the schedule a class in every five mins, then use below CRON expression.

How to run follow below process:


Go to your developer console -> Open Execute Anonymous Window -> Copy and Paste Below code and click on execute button

Simply say, Run below CRON expression from your developer console:


System.schedule('Schedule Job Name 1',  '0 00 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 2',  '0 05 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 3',  '0 10 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 4',  '0 15 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 5',  '0 20 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 6',  '0 25 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 7',  '0 30 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 8',  '0 35 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 9',  '0 40 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 10', '0 45 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 11', '0 50 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 12', '0 55 * * * ?', new ScheduleBatchApexClassExample());

After this, if you want To check apex class in scheduled or not then:

Export VisualForce Data into Excel Sheet in 3 Easiest Steps

Export VisualForce Data into Excel Sheet in 3 Easiest Steps

One of the most common Business requirements is to export a VisualForce page with data into an Excel sheet.

If you want to import CSV file In Salesforce using Apex then check Import CSV file In Salesforce using Apex in 3 Easiest Steps

Here in this blog, I am exporting contact data into AllContacts.xls sheet using Visualforce page.

To export data from a Visualforce page, the only real change that you have to make to the page is to change the content type of the page to “application/vnd.ms-excel” and also set a file name. 
<apex:page contentType=”application/vnd.ms-excel#AllContacts.xls”> </apex:page>

By simply modifying the ContentType attribute on the <apex:page> tag, your Visualforce page code will automatically generate an Excel document and download it automatically. 

For example, the following code will create a table of Contact data for a given Account. After # in the contentType attribute value, it is the name of the excel file that will be generated and you also need to mention the file extension like .xls.

Here is the sample code:

Step 1:


To do this, lets start off with a super simple controller. Create Apex Class ExportAllContactsHandler

public class ExportAllContactsHandler{
    public List<Contact> lstContact {set;get;}
   
    public ExportAllContactsHandler(){
        // Here I added limit 10, you can add filter criteria which you want
        lstContact = [Select Id, Name, Email, Phone From Contact Limit 10];   
    }

}

Step 2: 

Create Visualforce Page with name Export_All_Contacts:

<apex:page controller="ExportAllContactsHandler" contentType="application/vnd.ms-excel#AllContacts.xls" cache="true">
    <apex:pageBlock title="Export All Contacts">
        <apex:pageBlockTable value="{!lstContact}" var="objContact">
            <apex:column value="{!objContact.Name}"/>
            <apex:column value="{!objContact.Email}"/>
            <apex:column value="{!objContact.Phone}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Step 3:

You can click on Preview button which is on Visualforce page 
OR 
You can Go to the URL and type (Change the yoursalesforceinstance with your salesforce org URL)

https://yoursalesforceinstance.com/apex/Export_All_Contacts

AllContact.xls downloaded automatically into your local system.

When you have created this Visualforce page and you go to view the page, your browser should automatically download the .xls file. When you try to open it, you will most likely be presented with an error!
Click OK and open the file.

Its very simple code here. You have to keep only 1 things in your mind while Export VisualForce Data into Excel Sheet.
Here in query, I have added LIMIT statement in the controller to limit the Contact returned to 10. If your Salesforce org have 10000 contacts then you will face issue like, "Collection size xxxx exceeds maximum size of 1000".
We should always limit the query here so as not to reach the View State limit, but in this case it is done to to keep the file returned nice and simple for later processing. 
What are the Best practices to optimize view state, then check this : An Introduction to Visualforce View State in Salesforce

Import CSV file In Salesforce using Apex in 3 Easiest Steps

Import CSV file In Salesforce using Apex in 3 Easiest Steps

Salesforce does not read the excel file into apex. To overcome for this either we can covert excel file to CSV and import csv file using below code.

We can import data using data loader But sometime there is requirement when end users do not want to use Apex Data loader. 

Client want custom page to load data in salesforce.

Here I am explaining Import CSV file In Salesforce using Apex. Below is the code snippet which import CSV file from apex. I have created one visual force page and controller associated with it. 

Visual force page have Import Accounts into Salesforce button. 
Once user click on the button, I am sending email using apex code. 

Step 1: Create Apex Controller

public class importDataFromCSVController {

  public Blob csvFileBody{get;set;}
  public String csvAsString{get;set;}
  public String[] csvFileLines{get;set;}
  public List<account> accountlist{get;set;}

  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    accountlist= New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
             // Read CSV file body and store it in variable
              csvAsString = csvFileBody.toString();
   
            // Split CSV String to lines
             csvFileLines = csvAsString.split('\n'); 
           
            // Iterate CSV file lines and retrieve one column at a time.
             for(Integer i=1; i < csvFileLines.size(); i++){
               Account accObj = new Account() ;
               String[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               accountlist.add(accObj);   
             }
            // if all correct then insert Account into Org
             if(accountlist.size()>0)
             insert accountlist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data into Salesforce. Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Step 2: Create Visual force Page

<apex:page controller="importDataFromCSVController" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Accounts into Salesforce" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accountlist}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Phone}" />
              <apex:column value="{!acc.Fax}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Step 3: Download csv file into local machine. Click here to download CSV file.

Schedulable Batch Apex In 3 Easy steps In Salesforce

Schedulable Batch Apex In 3 Easy steps In Salesforce

  • There are three main steps involved in this

1. Write Batch Class
2. Write a Scheduled Apex which execute the above Batch Class
3. Schedule the class from the Developer Console or from UI

So here we go...

Step 1. Write Batch Class

global class BatchApexClassExample implements Database.Batchable<SObject>{

 global Database.QueryLocator start(Database.BatchableContext BC) { 
  String soqlquery = 'SELECT Id, name, phone FROM Account';
  return database.getquerylocator(soqlquery);
 }
 // The batch job executes and operates on one batch of records
 global void execute(Database.BatchableContext BC, List<SObject> scope) { 
   // your logic
   System.debug('In BatchApexClassExample - Execute Method ');
 }
 // The batch job finishes
 global void finish(Database.BatchableContext BC) { 
   System.debug('BatchApexClassExample Batch job completed successfully.');
 }
}

Step 2. Write a Scheduled Apex which execute the above Batch Class

global with sharing class ScheduleBatchApexClassExample implements Schedulable {
 global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new BatchApexClassExample(), 200);
 }
}

Step 3. Schedule the class from the Developer Console or from UI
  •  From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button
  •  From Developer Console, check below 
 Execute a schedulable Apex class with System.schedule method

 System.schedule('ScheduleBatchApexClassExampleScheduler', '0 0 * * * ?', new ScheduleBatchApexClassExample());

Good job, we are done. 

If you want to see your batch job scheduled then 

  • Go to Setup—>Monitor –> Scheduled Jobs

If you want to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.


Yes I have solution for it. Small code to do so for every 5 minutes.