Concepts or coding lessons of Salesforce that you can implement easily

Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Secret Trick To Retrieve Fields For Sobject Using Apex

Recently, I had a use case like dynamically determine what fields had been queried or set on a sObject. Unfortunately, we can not query or SOQL to object to retrieve fields metadata. 

Apex has a class called Schema. It includes all the schema of your organization. Objects, their fields, field type etc. can all retrieved using schema class.

Alternative of hard-coding this list, which is not sustainable or repairing it regularly, a good approach is to use Salesforce field describe results methods.

In the below example I am going explain to you how to Get all fields for sObject using Apex by utilizing the metadata available from the DescribeSObjectResult class. 

Follow the below steps:

Step 1: Create Apex Controller

public class RetrieveFieldsController
{
public List<String> objFields { get;set; }
public void retrieveFields(){
  // Object Name whose fields we have to retrieve
  String objectName = 'Account'; 
  Map<String , Schema.SObjectType> schemaGlobalDescription = Schema.getGlobalDescribe();
   Schema.sObjectType objType = schemaGlobalDescription.get(objectName); 
   Schema.DescribeSObjectResult objDescribeSObjectResult = objType.getDescribe(); 
   Map<String , Schema.SObjectField> mapFieldList = objDescribeSObjectResult.fields.getMap();  
  for(Schema.SObjectField field : mapFieldList.values())  
  {  
    Schema.DescribeFieldResult fieldResult = field.getDescribe(); 
// isAccessible () Returns true if the current user can see this object, false otherwise
      if(fieldResult.isAccessible())
        objFields.add(fieldResult.getName());
   }
  
  System.debug('objFields--'+objFields);
 }
}

Step 2: Create Visualforce page

<apex:page controller="RetrieveFieldsController" action="{!retrieveFields}">
   <apex:form>
      <apex:pageblock>
           <apex:pageblockTable value="{!objFields}" var="obj">
              <apex:column value="{!obj}"/>
           </apex:pageblockTable>
      </apex:pageblock>
   </apex:form>

</apex:page>



The following steps show you how you can work with describe information in Salesforce Apex class:
  1. Generate a list or map of tokens for the sObjects in your Salesforce organization (see Accessing All sObjects.)
  2. Determine the sObject which you need to access.
  3. Generate the describe result for the sObject you selected.
  4. If required, then generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.)
  5. Then Generate the describe result for that field the code needs to access.
If you want to retrieve Names of All Objects Using Apex then check my post:



In Details Schema.getGlobalDescribe() :


It returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization.

The map has the following characteristics:
  • It is dynamic, that is, based on permissions, it generates at runtime on the sObjects currently available for the organization.
  • The sObject names are case insensitive.
  • The keys are prefixed by the namespace, if any.*
  • The keys indicate whether the sObject is a custom object.
Note: If the getGlobalDescribe method is called from an installed managed package, it returns all the sObject names and tokens for Chatter sObjects, such as NewsFeed and UserProfileFeed, even if Chatter is not enabled in the installing salesforce organization. But if the getGlobalDescribe method is called from normal apex class which is not part of installed manage package then this is not true.


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.

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.

7 Easy Steps to Generate Apex Class From WSDL In Salesforce

Steps to generate an Apex class from a WSDL :

1. Take the external WSDL document and store in local computer or laptop.
2. Go to Setup -> Build -> Develop -> Apex Classes
3. Click on Generate from WSDL button.




4. Click on Choose File button and Select a WSDL document 
    which you stored into your system.
5. Click on Parse WSDL button.


The application generates a default class name for each namespace in the WSDL document and displays if there are any errors. If the WSDL contains schema types or constructs that doesn`t support by Salesforce Apex classes, or if the resulting classes exceed the 1 million character governor limit of Salesforce on Apex classes then Parsing fails . For example, Error will be like the Salesforce SOAP API WSDL cannot be parsed.

6. Modify the class names if you want. While you can save more than 1 WSDL namespace into a single apex class. To do this you have to use the same class name for each namespace, Apex classes can not contains more than 1 million characters total, as this is governoe limit of salesforce.

7. Click Generate Apex button. The final page of that wizard shows which classes were successfully generated from WSDL. It also contains errors if any from other apex classes. The page also provides a Salesforce link to view successfully generated apex classes.

Note: The size of any WSDL document can be at most 1MB. When the document is parsed to apex class, then each namespace becomes an Apex class.

Apex classes can be automatically generated from a WSDL document that is stored on a local hard disk or network. Creating an apex class by consuming a WSDL document allows developers to send callouts to the external Web service in their Apex code.

The WSDL file that you provide may contain a SOAP endpoint location that references an outbound port.

For security purpose, Salesforce restricts those outbound ports you may specify to one of the following:

  • 80: This port only accepts HTTP connections.
  • 443: This port only accepts HTTPS connections.
  • 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.

Note the following about the generated Apex:


  • If a WSDL file contains an Apex reserved word, then while Apex class is generating that word is appended with _x. For example, a limit reserved word in a WSDL document converts to limit_x in the generated Apex class. Check out the Salesforce document to check details on of handling characters in element names in a WSDL that are not supported in Salesforce Apex variable names.
  • If any logic which is in the WSDL has an output message which has more than one element, then the generated Apex wraps the elements in an inner class. The Apex method that represents the WSDL logic returns the inner class instead of the individual elements.
  • Since periods that is (.) are not allowed in Apex class names, If any periods present in WSDL names used to generate Apex classes are replaced by underscores (_) in the generated Salesforce Apex code.
If you want more details then check WSDL documentation provided by 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.

Simplest Way To Find Number of Days Between Two Dates in Salesforce

To Find Number of Days Between Two Dates in Salesforce, it provides daysBetween() function which returns the number of days between the Date that called the method and the specified date.

For Example:


Date startDate  = Date.valueOf('2016-05-12'); // 12th May 2016
Date endDate   = Date.valueOf('2016-05-30'); // 30th May 2016

Integer noOfDaysBetweenDates = startDate.daysBetween(endDate);

System.debug('No Of Days--- '+noOfDaysBetweenDates);

Output : 

No Of Days--- 18

Some other Date methods which can help you in other requirements.

The following are methods for Date :


addDays(additionalDays) :
This function adds the specified number of additional days to a Date.
Syntax : public Date addDays(Integer additionalDays)

addMonths(additionalMonths) :
This function adds the specified number of additional months to a Date .
Syntax : public Date addMonths(Integer additionalMonths)

addYears(additionalYears) :
This function adds the specified number of additional years to a Date .
Syntax : public Date addYears(Integer additionalYears)

day() :
This function returns the day-of-month component of a Date .
Syntax : public Integer day()

dayOfYear() :
This function returns the day-of-year component of a Date .

daysBetween(secondDate) :
This function returns the number of days between the Date that called the method and the specified date.

daysInMonth(year, month) :
This function returns the number of days in the month for the specified year and month (1=Jan) .

format() :
This function returns the Date as a string using the locale of the context user .

isLeapYear(year) :
This function returns true if the specified year is a leap year .

isSameDay(dateToCompare) :
This function returns true if the Date that called the method is the same as the specified date .

month() :
This function returns the month component of a Date (1=Jan) .

monthsBetween(secondDate) :
This function returns the number of months between the Date that called the method and the specified date, ignoring the difference in days .

newInstance(year, month, date) :
Constructs a Date from Integer representations of the year, month (1=Jan), and day .

parse(stringDate) :
Constructs a Date from a String. The format of the StringDate depends on the local date format .

today() :
This function returns the current date in the current user's time zone .

toStartOfMonth() :
This function returns the first of the month for the Date that called the method .

toStartOfWeek() :
This function returns the start of the week for the Date that called the method, depending on the context user's locale .

valueOf(stringDate) :
This function returns a Date that contains the value of the specified String .

valueOf(fieldValue) :
Converts the specified object to a Date. Use this method to convert a history tracking field value or an object that represents a Date value .

year() :

This function returns the year component of a Date .

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.

5 Quick Steps To Install Apex Data Loader.

There are Various ways to Export or Import data in Salesforce.

In a market, you can get many tools which help you to export or import data in Salesforce. 
Each tool has their Pros and Cons. 
One of the Most popular Exports or Import data tool is Data loader which is a free tool. 
Every Salesforce Admin and Developer use this tool frequently wherever it requires.

Data Loader is a client app for the bulk import and export of data.
With data in a comma-separated value (CSV) file, Data Loader can create, edit, or delete Salesforce records for any standard or custom object.

Data Loader exports Salesforce records into CSV files. 
You can then edit those CSV files or use them as templates for importing data into Salesforce.

Right now, Salesforce has two user interface i.e. Salesforce classic interface and Lightning experience interface.
Below are the steps explain how to install data loader in Salesforce classic interface and in Lightning Experience interface. 

Install Data Loader using Salesforce Classic interface:



1. Go to Setup.
2. Under "Administer" click Data Management | Data loader.
3. Choose the appropriate version based on your computer.
     a. Download Data Loader for Windows
     b. Download Data Loader for Mac
4. Save the file on local PC or laptop.
5. Double click on downloaded file and follow the Installation process of data loader.

Install Data Loader using Lightning Experience interface:


1. Click Setup Lightning Experience Setup menu icon | Setup Home.
2. Under "Administration" option Select Data | Data Loader.
3. Choose the appropriate version based on your computer
     a. Download Data Loader for Windows
     b. Download Data Loader for Mac
4. Save the file on local PC or laptop.
5. Double click on downloaded file and follow the Installation process of data loader.

Done !!!



Other tools which export or import data into Salesforce:



I have grouped those tools into four categories. Each has their Pros and Cons.
  1. Free Tools
  2. Your Own Tools
  3. ETL Tools
  4. Paid Tools
1. Free tools: If you don`t want any budget to buy paid tool then use free tools.
  • Salesforce Data loader:- The tool gives you a nice user interface to pick the object and fields and criteria for the data you want to export, or write your own SOQL query. 
  • Reports:- Simplest option, create report. Run report and then export it using salesforce.
  • Data Export:- Go to setup and under the data management option you can find Data export option.
  • Workbench
2. Your own tools:
3. ETL ToolsETL stands for Extract-Transform-Load. This tools are mostly for developer because more complicated to setup and use for the uninitiated than the other options already described. Below are not Salesforce specific but they have connectors to Salesforce.
  • JitterBit
  • Informatica
4. Paid Tools:
  • Enabler 4 Excel
  • X-Author by Apptus
  • Force.com Excel Connector
Do you know of other tools or methods of exporting or importing Salesforce data? I’d love to hear about it.

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.

3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce

Messaging.Sendemail() : 


This method Sends the list of email objects instantiated which of either SingleEmailMessage or MassEmailMessage methods and returns a list of SendEmailResult objects.


Below are the easy steps or you can say template to Send an email with Apex with an attachment:


  • Create a list for email messages. 
  • Then create your emails.
  • Attach attachment to emails.
  • One by one (maybe in a loop)
  • Add them to that list. 
  • Finally send them using a Messaging.sendEmail(yourList).

Here, I will give you a step by step walk through of Send Emails With Attachment From Your Apex Class In Salesforce.
I have created one visual force page and controller associated with it. Visualforce page have Send Email With Attachment button. 

Once user click on the button, I am sending email with attachment using apex code. 

Step 1:

Create Apex Class with name DemoSendEmailWithAttachment. Copy and Paste below code snippet: 

public class DemoSendEmailWithAttachment
{
    public void SendEmailWithAttachment()
    {
        String subject = 'Closed won opportunities with Amount';
        String body = 'This is testing for Send emails with attachment from your apex class in Salesforce';

    // Creating the CSV file
    String finalstr = 'Id, Name, Amount \n';
String attName = 'Closed won opportunities.csv';

// get all the closed won opportunities
    for (Opportunity myOpportunity : [SELECT ID, Name, Amount FROM Opportunity WHERE StageName = 'Closed Won'])
        {
    string recordString = '"'+myOpportunity.id+'","'+myOpportunity.Name+'","'+myOpportunity.Amount+'"\n';
            finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
// Create the email attachment    
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Set the paramaters to 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 );

// Attach file using setFileAttachments function
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
    }
}

Step 2:

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

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

https://yoursalesforceinstance.com/apex/DemoSendEmailWithAttachment

Click on Send Email With Attachment button





Done !!!

Make sure all contacts have valid email address else email will bounced.

Before implementing mass email in Salesforce, you have to consider Email limits.

The maximum size of email attachment is 3 MB.
The create call restricts these files to a maximum size of 25 MB and For a file attached to a Solution record, then the file limit is 1.5 MB.

The API supports attachments on email message in create, delete, or update methods. The query call returns attachments parented by email, if the user performing the query has the “Modify All Data” permission else it does not returns attachments.

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.




Learning Send Mass Emails From Your Apex Class In Salesforce Is Not Difficult At All

Send mass email in Salesforce using apex code is easy now.


I have uploaded multiple contact Using data loader. I got one requirement to send an email with body to all contacts which are inserted.
Obviously we can add logic into Contact trigger on After Insert event to send mail.
In this blog, I am going to tell you about how to send mass emails from apex class.
I would like to share the approach which I used.

In my last blog, I have covered 3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce.

Below is the code snippet which sends an email to single user from apex. I have created one visual force page and controller associated with it. Visualforce page have Send Email button. 
Once user clicks on the button, I am sending email using apex code. 


Try this for sending emails to all contacts in my Salesforce org.

Step 1:

Create Apex Class with name DemoSendMassEmail and Paste below code snippet.

public class DemoSendMassEmail
{
     public void SendEmail()
     {
        String subject = 'Testing Mass email demo';
        String body = 'This is testing for Send mass emails from your apex class in Salesforce';       
        // Create a master list to store the emails that we will send
        List<Messaging.SingleEmailMessage> masterListMails =  
        new List<Messaging.SingleEmailMessage>();
        for (Contact myContact : [SELECT ID, Email FROM Contact])
        {
          // Define the email
          Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
           // Set list of peoples who should recieve an email
           List<String> sendTo = new List<String>();
           sendTo.add(myContact.Email);
           email.setToAddresses(sendTo);

            email.setSenderDisplayName('Official Nitish Account');

            // Sets the paramaters of the email
            email.setSubject( subject );
            email.setPlainTextBody( body );

            // Add your email address into the master list
             masterListMails.add(email);
         }
       // Sends mass emails
       Messaging.sendEmail(masterListMails);
      }
}

Step 2:

Create a VF page named as DemoSendMassEmail and paste the code snippet below.

<apex:page Controller="DemoSendMassEmail">
    <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













3 Easy steps and we are done !!!


Make sure all contacts have valid email address else email will bounced back.

Before implementing mass emailSalesforceorce, you have to consider Email limits.


Email Limits in Salesforce:

  • Based on Greenwich Mean Time (GMT), you can send mass email up to a maximum of 5,000 external email addresses per day per org.
  • The single, as well as mass email limits, do not count unique addresses as one into account. For example, if you have nitishtest@example.com in your email 10 times, that counts as 10 against to the limit.
  • You can send as many amounts of email you want to your org’s internal users including portal users.
  • You can send mass email messages only to contacts, person accounts, leads, as well as your org’s internal users.
  • In Developer Edition orgs and orgs evaluating Salesforce during a trial period, you can send maximum 10 mass email to external email addresses per day.
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.