Blog-2
Salesforce Apex Coding
- July 26, 2024
- Posted by: Peoplewoo Skills
- Category: Administrator
Apex Testing
Examples
Assert Methods
Basic Test Class
This test class will test the IsBlank(…) method of SomeClass. Below is the example SomeClass. This class has only the one, basic static method, but you will be unable to deploy it to a production instance for use until you have reached the code coverage threshold.
As one can see, this method is simply a if statement with three branches. To write an effective test class, we must cover each branch with code, and use System.assertEquals(…) statements to verify that the proper data was received from IsBlank(…).
Using testSetup
You can use a method annotated with @testSetup to write code that will have been executed before each test run:
Using static blocks
While you can use the @testSetup annotation to designate a method to be run before tests are executed, this method will usually only be run once. If you need code to be run before each test, you can use a static block:
Assertion Methods
System.assert can be used to check that a boolean expression evaluates to true:
System.assertEquals and System.assertNotEquals can be used to check equality of two values. The expected value is passed as the first parameter, and the value under test is passed as the second.
Apex Triggers
Syntax
- trigger <name> on <object-api-name> (<events>) { // your trigger logic }
Parameters
Examples
Basic trigger
Trigger context variables
Manipulating records that fired the trigger
Approval Process Objects
Remarks
Approval Process is a very amazing feature in Salesforce to automate the business process. An approval process is a set of the steps necessary for a particular record to be approved or rejected by approver or set of approvers.
A step can apply to all records included in the process, or just records that meet certain administrator-defined criteria. An approval process also specifies the actions to take when a record is approved, rejected, recalled, or first submitted for approval.
ProcessDefinition and ProcessNode objects act as a template and store the master configurations for Approval Process itself.
Examples
ProcessDefinition
Represents the definition of a single approval process. Use this object to read the description of an approval process. The definition is read-only. We can not modify the record created in ProcessDefinition Object. But we can describe, query, search and retrieve the approval processes information.
~ Query ~
The records are created when we create a new approval process using Salesforce user interface of Approval Process.
ProcessNode
Represents the Process Steps created for particular approval process(ProcessDefinition). This object is used to read the description of process step. In simple words ProcessNode records describes a step in a process definition. We can describe, query, search and retrieve the approval processes Steps.
~ Query ~
As we can see ProcessDefinitionId field is acting like a foreign key which is referring ProcessDefinition Object or Table for which steps or process nodes are created. This object is also read only as ProcessDefinition Object.
ProcessInstance
Represents an instance of a single, complete approval process. ProcessInstance record is created every time for particular object record which is submitted for approval. Its is also read-only object. We can describe, query and retrieve the approval processes Instance.
~ Query ~
All ProcessInstance fields are automatically populated once the record is submitted for approval, with two exceptions fields: CompletedDate and LastActorId that are populated only after the approval process instance is complete. The ProcessDefinitionId field is the reference or foreign key ID of the ProcessDefinition Object.
ProcessInstanceStep & ProcessInstanceWorkitem
Both objects ProcessInstanceStep & ProcessInstanceWorkItem are instances of process steps that are created for particular ProcessInstance. ProcessInstanceStep represents a step instance in an approval process (ProcessInstance) on which users has already acted and ProcessInstanceWorkItem represents a step instance in an approval process(ProcessInstance) on which is pending and users has to perform some action next on it. We can describe, query and retrieve the approval processes steps and workItems.
Query ~
ProcessInstanceHistory*
The ProcessInstanceHistory is the object which is neither searchable nor queryable & this is the read-only object which shows all steps and pending approval requests associated with an approval process (ProcessInstance). But we can use this object to replicate the related list functionality of the Salesforce user interface for approval processes which will be shown in my next blog post soon. We can use ProcessInstanceHistory for a single read-only view of the both ProcessInstanceStep and ProcessInstanceWorkitem objects. We can query ProcessInstanceHistory by querying it in a nested soql query on the parent ProcessInstance object. The nested soql query references StepsAndWorkitems, which is the child relationship name for ProcessInstanceHistory in the ProcessInstance object. This is very useful object to solve various business problems.
Query ~
Custom Settings
Remarks
Introduction
Unlike custom objects which have records based on them, custom settings let you utilize custom data sets across your org, or distinguish particular users or profiles based on custom criteria. This means, for example, that admins can edit hierarchy custom settings to deactivate Workflow / Validation Rules for single users or profiles, without having to switch them off for the whole org (see the Using Hierarchy Custom Settings To Disable Workflow / Validation Rules example above).
Validation rules commonly need to be disabled temporarily when:
- Code is updating old records, which were last edited before a validation rule was activated & therefore don’t meet the newer rule’s criteria.
- Code is inserting new records without the values required by a validation rule’s criteria.
Workflow rules commonly need to be disabled temporarily when:
- They would trigger an Email Alert or Field Update which would overwrite or interfere the changes you are making to the record.
Use of a custom setting grants admins some declarative control over code so one of the many use cases is that when utilized, they can make it unnecessary to deploy code in order to disable triggers (see the Using Hierarchy Custom Settings To Disable Apex Code example above).
A key benefit for developers is that custom setting’s data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, flows, Apex, and the SOAP API – see the Salesforce documentation.
The limits & considerations for custom settings are documented here.
List Custom Settings
It is possible to create List Custom Settings too, common use cases include storing two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. However Salesforce is now promoting the use Custom Metadata Types, instead of List Custom Settings.
When you go to create a new Custom Setting, the following message will be displayed
Tip: Use Custom Metadata Types for App Configuration
If you’re thinking of using list custom settings, consider using custom metadata types instead. Unlike list custom settings, you can migrate the records of custom metadata
types using using packages or Metadata API tools.
Custom Metadata Types have additional benefits vs List Custom Settings as described in this answer. And according to the lead developer of CMDs “There’s a lot more planned for custom metadata types than custom settings on steroids.”
Examples
Creating & Managing Custom Settings
Creation
To create a Custom Setting, go to:
Classic
Setup > Develop > Custom Settings > New
Lightning
Setup > Custom Code > Custom Settings > New
Create your setting (see the Remarks later in this document for the differences between Hierarchy & List custom settings). You can ignore the Visibility picklist, unless you plan to deploy your setting in a managed package.
To create your setting fields click the New button and follow the usual process for creating a custom field.
Management
Once you have created your field(s) you can start configuring the setting by clicking the Manage button.
It’s easier to manage the setting if you create a new view and include any fields that you’ve created to give yourself a comprehensive overview of the setting, at a glance. The Setup Owner is the user or profile that the setting applies to.
To manage the setting at the org level, click the New button above the Default Organization Level Value header (in red box below).
To manage the setting at the user or profile level, click the New button in the blue box below.
Using Hierarchy Custom Settings To Disable Workflow / Validation RulesÂ
Custom SettingÂ
Custom Setting Field
Custom Setting Field Value
Validation Rule
The rule can also be disabled for a whole Salesforce org –
In the above rule, both pieces of criteria must evaluate to TRUE in order for the rule to be triggered.
Since All_Opportunity_Disabled c checkbox will evaluate to TRUE when the running user’s profile is System Administrator, the rule will evaluate to FALSE.
Workflow Rules
The same approach can be applied in order to deactivate Workflow Rules.
Using Hierarchy Custom Settings To Disable Apex Code
Explanation
In this example a simple Trigger has been created to change the Close Date of an Opportunity, that’s about to be inserted or updated, to a date 10 days in the future.
The Apex Controller custom setting’s checkbox field enables the code to be disabled at the user / profile / org level.
Apex Class
Unit Test
Updating Hierarchy Custom Settings in Apex Code
You may wish to update your custom setting’s during the execution of your code, to switch off validation or workflow rules.
In the below code, I have created a Schedulable Apex Class which will update the Close Date of any Opportunities whose Close Date is less than or equal to 6 days from the current date, changing the date to 20 days in the future.
I will use my Custom Setting Val_Rule_Cntrlr c to deactivate any validation rules which would prevent me from updating the Opportunities that meet my criteria.
To make sure that my validation rules are being deactivated by the changes to my custom setting in my class, I have created a checkbox field Trigger_Validation_Rule c (which would not be visible to users or added to page layouts) & a validation rule with this criteria:
I then set the checkbox field to true when creating my Opportunities so that the rules criteria would be met, if the custom setting field is not edited by my code.
Date Time Manipulation
Examples
Easily Find Last Day of a Month
If you need to find the last day of the month, you can do complicated DateTime gymnastics or you can use the following method.
Say you want to find the last day of February 2021. Do the following:
This produces the following output in the Logs:
Global Variables in classes
Introduction
In this topic I would like to mention all possible global variables which can be used in Apex code. Like [UserInfo Class][1]. I suggest we just list a global classes/variables and links. If you know about a global class/variable but can’t find a documentation, please provide as much information as possible. [1]: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_userinfo.htm
Examples
UserInfo
getFirstName() – returns the context user’s first name. getLastName() – returns the context user’s last name.
Global Variables on Visualforce pages
Examples
$Resource
Use the $Resource variable to reference static resources.
Can be used in conjunction with the URLFOR function to reference files inside of a zipped static resource:
$Label
The $Label variable can be used to display text defined in your custom labels.
You can do formatting with labels as well. Suppose you have a custom label named
Welcome_Message defined as
You could use the label to display a formatted message:
$User
The $User variable gives you access to all the standard and custom fields on the User object for the currently logged in user.
Page Navigation with help of list wrapper class in sales force.
ntroduction
Slaesforce StandardSetController hold only List of sObject, It will not holdslist of wrapper class object. Below source code demonstrates the usage of Paginating using Wrapper Class in sales- force.
Examples
Pagination Controller
Code example : Now Start with Creating the Pagination Controller
i am going to show all the contacts in the form of pagination and there should be one checkbox for each contact to selected or deselect contact to perform delete operation on contacts. So i need to be create a wrapper class to hold contact and Boolean Variable for selection. First create Wrapper class for controller Pagination Insert below code into pagination controller.
Now Retrieving Data in Apex to Paginate with the help of StandardSetController. The StandardSetController is an extremely powerful tool with built-in functionality that you can use to greatly simplify the custom code in your Visualforce pages. Because the server returns only the data for the page being requested, the StandardSetController can significantly reduce view state, especially compared to the view state you would get while using SOQL.
Now you have the contacts in the Variable setCon , whenever your requested for setCon.getRecords() it will retrieve the first 10 contact records from the setCon. Here i have create simple wrapper class to show you the demo. You can create your own wrapper class based on requirement. But always you must be aware that ApexPages.StandardSetController hold only List of sObject, it will not hold the list of wrapper class object . That’s the reason i have written extra code below to accomplish this future in different way. Below code convert list of contacts into list of wrapper class objects, So that when ever you call contacts in visual force page it will receive the list of wrapper class object.
Now you have written code for generating result But how to navigate across the page? This can be done with easy step with ApexPages.StandardSetController.Look at the below code beauty of the StandardSetController, No need to maintain page number,offset and limit etc.. Just use the StandardSetController methods. Copy the below code into Pagination controller.
Your almost done with Paginating the contacts. Last few methods i have added to fulfill my entire page functionality. As i mention earlier we have additional checkbox for selecting contact and perform delete operation on selected contacts.
SalesForce CI Integration
Introduction
Place to use Jenkins and Sonar for CI
Examples
How to configure Jenkins to deploy code on Development or Production org ?
How we can use jenkins in our SalesForce product development. What are the tools plugins are available for Jenkins Integration How to solve CI configuration issue. etc
Jenkins CI tools which can be used for SalesForce Automation
- Jenkins: The leading open source automation server, Jenkins provides hundreds of plugins to support building, deploying and automating any project.
- Sonar Qube: SonarQube provides the capability to not only show health of an application but also to highlight issues newly introduced.
- Apache Ant: Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other.
- Apache Maven: Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.
- SfApexDoc: Support for JavaDoc like documentation creation tool. Can be used by Ant/Jenkins to create Documents.
- JUnit format Report for APEX: Extends the Force.com com.salesforce.ant.DeployTask to accept an optional junitreportdir argument that defines the folder that a JUnitReport XML file is output into. This file can be consumed directly by the Jenkins continuous integration tool to produce trend graphs and test result details or by the JUnitReport Ant task.
- Version Control System: Can use GIT, SVN or any other Version Control system
- PMD Apex: Contains the PMD implementation to support the Apex programming language.
- Sonar for Apex(enforce-sonarqube-plugin): The plugin has support for the Apex language grammar, the current list of checks is focused mainly on test components. The support for more SFDC components is in progress.
Â
Salesforce Object Query Language (SOQL)
Syntax
- SELECT Id FROM Account
- SELECT Id, Name FROM Account
- SELECT Id FROM Account WHERE Name = ‘SomeAccountName’
- SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account
- SELECT Id, Name FROM Account WHERE Id = :apexVariableName
Examples
Basic SOQL Query
This will return the Id and Name fields from the Account table. No filtering or sorting will be applied.
SOQL Query With Filtering
This will return the name of all active Users.
This will return Contacts created on or after January 1st, 2016.
This will return the first 100 Accounts from an unordered list.
This will return Leads with a phone number matching the specified format. “%” acts as a wild card character.
Using LIKE ‘% %’ also enables a developer to replicate a CONTAINS( ) formula.
Will return Leads with a lead source that contains Google i.e. ‘Google AdWords’ & ‘Google Natural Search’.
SOQL Query With Ordering
Using SOQL to Construct a Map
A very useful feature many people overlook is the ability to construct a Map using a SOQL query.
When you run this code, accounts then contains a Map of your Account objects, keyed on Id. The output to the debug log would look similar to this:
You are now able to look up the Account objects using their Id. Furthermore, if you want a collection of unique IDs, you can call the keySet() function of the Map class, like so:
which looks something like this in the debug log:
This is very useful when you need to query to get records and access them repeatedly in your code.
SOQL Query to Reference Parent Object’s Fields
When object’s are linked by a lookup or master-detail relationship, the parent records field’s can be referenced from the child record or ‘base object’ in a query. This is also known as upwards traversal.
It’s possible to traverse five records upwards.
When the base object is a custom lookup field, the c in field’s name Primary_Influencer c, for example, will be changed to r.
SOQL Query to get child Records
SOQL Queries in Apex
To perform a query in Apex, surround the query with square brackets. The result can be assigned to a list, or to a single object.
Variable References in Apex SOQL Queries
To reference a variable in a query, add a colon (:) before the variable name.
Potential Exceptions in Apex SOQL Queries
When assigning to a single object, a query that returns anything other than a single row will throw a QueryException.
Attempting to use a field that you did not include in the query will throw a SObjectException
Using a Semi-Join
Selecting all accounts that have open opportunity records under them
Dynamic SOQL
You can execute a database query from a String rather than a regular SOQL expression:
Since dynamic SOQL queries are not compiled, their schema references are not validated, so it is preferable to use Apex variable interpolation using the :variable syntax where possible.
Â
Salesforce REST API
Introduction
Force.com REST API Documentation. Full list of API’s is here
Examples
OAuth2 access_token and list of services
To get OAuth2 access token simply do
curl https://login.salesforce.com/services/oauth2/token -d “grant_type=password” -d “client_id=myclientid” -d “client_secret=myclientsecret” -d “username=mylogin@salesforce.com” -d “password=mypassword123456”
You should get response something like
Then do
Tools for Development
Examples
IDEs
A list of available IDEs to create classes, triggers, Visualforce/Lightning pages/components.
- Force.com IDE – plugin for Eclipse
- JedIDE – plugin for IntelliJ IDEA & standalone Force.com IDE
- MavensMate – plugin for Sublime Text and Atom and VS Code
- FuseIT SFDC Explorer – This is a standalone tool
- Welkin Suite – This is a standalone tool;
- Illuminated Cloud – plugin for IntelliJ IDE
- Aside.io – Web-based IDE
- Cloud 9 – Web-based IDE
- VimAwesome – VIM plugin for Force.com
- HaoIDE – Sublime Text plugin for Force.com
- Metaforce – A lightweight Chrome app for Salesforce develoment
Browser extensions
- Salesforce Navigator (Google Chrome)
- Force.com Logins (Google Chrome, Firefox)
- Salesforce Developer Tool Suite (Google Chrome)
- Salesforce Lighting Components Inspector (Google Chrome)
- Salesforce Developer Tool Suite (Google Chrome)
- Salesforce Schema Builder Expander (Google Chrome)
- Boostr for Salesforce (Google Chrome)
- Salesforce API Fieldnames (GoogleChrome)
- Changeset Helper (Google Chrome)
- Salesforce Inspector (Google Chrome, Firefox)
- Salesforce Mass Editor (Google Chrome)
- Space (Google Chrome)
Debuggers
- Official Apex Debugger
- Realtime debugging
- Force.com IDE
- requires special licensing from salesforce
- Welkin Suit
- Log replay debugging
- Stand alone IDE
- Subscription required
- Illuminated Cloud:
- Log replay debugging
- JetBrains Extension
- Subscription required
- Salesforce Apex Debug
- Log replay debugging
- VS Code Extension
- Free and open source
- Currently still in alpha
Salesforce ETL tools
- Salesforce DataLoader
- Dataloader.io
- Jitterbit
- SFXOrgData
- DreamFactory Monarch
- Pentaho Kettle
- Talend
Static Analysis Tools
- CodeClimate: Cloud Service
- CodeScan: Cloud Service
- Clayton.io: Cloud Service
- VSCode Apex PMD: VS Code extension for realtime static analysis as you code
Apex PMD: command line core that runs most the above tools
Trigger Bulkification
Examples
Bulkification
If you do row-by-row processing in Salesforce, you’ll probably reach the governor limit quickly. This is especially true with triggers and things that fire when you don’t expect them. One documented method of escaping the governor limit is bulkification.
Note: The following information is based on the official Salesforce docs.
Bulkifying Apex code means making sure that the code properly handles more than one record at a time. When a batch of records initiate Apex, a single instance of that Apex code is executed, but that instance needs to handle all of the records in that given batch.
Not Bulkified:
Bulkified:
Visualforce Page Development
Examples
Basic page
A basic Visual Force page can be created like this:
Using Standard Controllers
If your page is for displaying or editing information about a particular type of record, it may be helpful to use a standard controller to reduce the amount of boilerplate code you need to write.
By using a standard controller, your page will be displayed with an ?id=SALESFORCE_ID parameter, and you automatically get access to all merge fields on the record.
Add a standard controller to your page by specifying the standardController attribute on
<apex:page>:
You also get the standard controller methods for free:
- cancel() – returns the PageReference for the cancel page (usually navigates back to a list view)
- delete() – deletes the record and returns the PageReference for the delete page
- edit() – returns the PageReference for the standard edit page
- save() – saves the record and returns the PageReference to the updated record
- view() – returns the PageReference for the standard view page
You can use them like this:
Working with External Systems
Examples
Making an outbound callout
This is an example on how to call a web service from salesforce. The code below is calling a REST based service hosted on data.gov to find farmers markets close to the zipcode.
Please remember in order to invoke a HTTP callout from your org, you need to tweak the remote settings for the org.
Credits