Concepts or coding lessons of Salesforce that you can implement easily

Showing posts with label visualforce page. Show all posts
Showing posts with label visualforce page. Show all posts

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 below code snippets 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 after opening the vf page and you also need to mention the file extension like .xls.

Here is the sample code:

Step 1:


To do this, let's 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.

It's very simple code here. You have to keep only 1 things in your mind while Export VisualForce Data into Excel Sheet.
Here in the query, I have added the LIMIT statement in the controller to limit the Contact returned to 10. If your Salesforce org have 10000 contacts then you will face an issue like, "Collection size xxxx exceeds the 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 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

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Understand How To Send Emails From Your Apex Class In Salesforce Before You Start

Sending an email from Apex Class is so easy.


The Apex Messaging.SingleEmailMessage class handles the email functionality available to Salesforce.
Basically there are two categories
  • SingleEmailMessage - This class is used when a use case requirement to send an email to a single person. This contains methods for sending single email messages.
  • MassEmailMessage - This class is used when a use case requirement to send an email to a group

Here I am explaining SingleEmailMessage category. Below is the code snippet which sends an email to single user from apex. I have created one visual force page and controller related to it. Visual force page have Send Email button. 
Once user clicks on the button, I am sending email using apex code. 
Try this for sending emails to a single user.


Step 1:

Create Apex Class with name DemoSendEmail. Paste below code snippet.

public class DemoSendEmail
{
     public void SendEmail()
     {
        String subject = 'Testing email demo';
        String body = 'This is testing for Send emails from your apex class in Salesforce';       
                                   
        // Define the email
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
        // Now sets the below paramaters of the email object
        email.setSubject( subject );
        // Here I am accessing current user email id to whom we are sending email
        email.setToAddresses( new String[] {UserInfo.getUserEmail()} );
        email.setPlainTextBody( body );
        // Sends the email
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  
      }
}

Step 2:

Create a VF page named as "DemoSendEmail" and paste the code below.

<apex:page Controller="DemoSendEmail">
    <apex:form>
         <apex:commandButton value="Send Email!" action="{!SendEmail}"/>
     </apex:form>
</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)


Click on Send Email button











Done !!!


Explanation about 
SingleEmailMessage:


The following are methods for SingleEmailMessage.

  • setBccAddresses(bccAddresses) : This is Optional. This contains list of blind carbon copy (BCC) addresses. If the BCC compliance option is set in your org at the organization level, then the user cannot add any BCC addresses on standard messages. You will get the below error code: BCC_NOT_ALLOWED_IF_BCC_ COMPLIANCE_ENABLED. You can contact to your Salesforce representative for information on BCC compliance.
  • setCcAddresses(ccAddresses): This is Optional. This contains list of carbon copy (CC) addresses
  • setCharset(characterSet) : This is Optional . The character set for the email. If character set value is null, then the user's default value is used.
  • setDocumentAttachments(documentIds) : This is Optional and Deprecated. Instead of this use setEntityAttachments() instead.
  • setEntityAttachments(ids) : This is Optional.
  • setFileAttachments(fileNames): This is Optional.
  • setHtmlBody(htmlBody) : This is Optional.
  • setInReplyTo(parentMessageIds) : This is Optional.
  • setOptOutPolicy(emailOptOutPolicy) : This is Optional.
  • setPlainTextBody(plainTextBody) : This is Optional.
  • setOrgWideEmailAddressId(emailAddressId) : This is Optional.
  • setReferences(references) : This is Optional.
  • setSubject(subject) : This is Optional.
  • setTargetObjectId(targetObjectId): This is required if using a template, if not then its optional.
  • setToAddresses(toAddresses) : This is Optional. The maximum number of email addresses allowed in setToAddresses method is 100.
  • setTreatBodiesAsTemplate(treatAsTemplate) : This is Optional. If this set to true, then the plain text, subject, and HTML text bodies of the email message are treated as template data.
  • setTreatTargetObjectAsRecipient(treatAsRecipient) : This is Optional.
  • setWhatId(whatId)
For more SingleEmailMessage details check Salesforce documentation related to  : SingleEmailMessage

Enjoy! If you have any questions, comments, please feel free to let me know.
As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.



How Learning Enable Inline Editing In Visual Force Pages Could Save Your Money And Time

how to do it in salesforce
Inline editing in visualforce page can be done by two ways provided by Salesforce :

1. The <apex:detail> component has an attribute that activates inline editing.

2. The <apex:inlineEditSupport>component provides inline editing functionality to several container components.

Only Visualforce pages version 21.0 and above support inline editing.


1. Inline editing using <apex:detail>:



<apex:page standardController="Account">
     <apex:detail subject="{!account.Id}" relatedList="false" inlineEdit="true"/>
</apex:page>

Move your mouse cursor on the field which you want to edit, you will notice that pencil icon which allows to you edit their content without clicking on Edit button. Non-editable cells display a lock icon. Just double click on the editable field, modify the content of the field and click on Save button which commits your record in the Salesforce database.

Keep in mind while executing above vf page, for this page to display account data, the ID of a valid account record must be added as a query parameter in the URL for the page. 

For example: in my case United Oil & Gas, Singapore account have id001i000000eJLL4.


So my URL become :






2. Inline editing using <apex:inlineEditSupport>:


You can use <apex:inlineEditSupport> provides inline editing support to <apex:outputField>.
If you want to use <apex:inlineEditSupport> then this component must be in <apex:form> tag.
This support for <apex:dataList>, <apex:dataTable>, <apex:outputField>, <apex:repeat> within <apex:inlineEditSupport> tags.

Below is the example of <apex:inlineEditSupport>

Create Visual force page: Copy below code and save it. Click on preview button and you will be able to test inline editing.

<apex:page standardController="Account" recordSetVar="records" id="thePage"> 
 <apex:form id="theForm"> 
   <apex:pageBlock id="thePageBlock"> 
    <apex:pageBlockTable value="{!records}" var="record" id="thePageBlockTable"> 
         <apex:column >
            <apex:outputField value="{!record.Name}" id="AccountNameDOM" /> 
            <apex:facet name="header">Name</apex:facet>
          </apex:column>
 <apex:column >
  <apex:outputField value="{!record.Type}" id="AccountTypeDOM" /> 
  <apex:facet name="header">Type</apex:facet>
 </apex:column>
 <apex:column >
  <apex:outputField value="{!record.Industry}" id="AccountIndustryDOM" />  
  <apex:facet name="header">Industry</apex:facet>
 </apex:column>
  <apex:inlineEditSupport event="ondblClick" 
     showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" /> 
</apex:pageBlockTable> 
<apex:pageBlockButtons > 
 <apex:commandButton value="Edit" action="{!save}" id="editButton" />
 <apex:commandButton value="Save" action="{!save}" id="saveButton" />
 <apex:commandButton value="Cancel" action="{!cancel}" id="cancelButton" />
</apex:pageBlockButtons> 
   </apex:pageBlock> 
  </apex:form>
</apex:page>

If you want to execute above visualforce page, then you have a to add parameter to the Visualforce page with a valid Account record in the URL. 

For example, if 001i000000eJLL4 is the Account ID, the resulting URL should be: 

https://Salesforce_instance/apex/myPage?id=
001i000000eJLL4

Check out the Visualforce Developer's Guide Quick Start Tutorial of Salesforce for more information.


Below are some cases which does not support the inline editing:

  • If you do not have Field level security or FLS on field i.e. you have read only access but inline editing allow you to edit that field. When you try to save that record, salesforce throw an error like Insufficient privilege error message. For ex. Account have field Phone and you have read only access through Field level security. You can edit this field but after clicking on save button Insufficient privilege error message displayed by Salesforce.
  • Standard rich text area (RTA) fields are not supported by inline editing feature.
  • Some standard objects does not support an inline editing.
  • All fields on Task object except subject field does not support inline editing.
  • All fields on Event object except subject field and Description field does not support inline editing.
  • Inline editing is not supported in Dashboards and Setup pages.
  • Do not mix inline edit-enabled fields with regular input fields from the same dependency group. For example, do not mix a standard input field for a controlling field with an inline edit-enabled dependent field.
Enjoy! If you have any questions, comments, please feel free to let me know. 
As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Next post: How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best