Parsing JSON in Salesforce Apex is an important part of salesforce development and is used to integrate data into Salesforce. In this post, we will learn how to parse JSON in Apex to consume external API data in Salesforce.
JSON (JavaScript Object Notation) is a text-based data interchange format that is used to transmit, transport and store data. It is commonly used to exchange data between web applications, client and server endpoints, database systems and more.
The best way to parse JSON data
Let’s see an example:
public class MyClass {
public String field1;
public String field1;
public static MyClass parse(String json) {
return (MyClass) System.JSON.deserialize(json, MyClass.class);
}
}
When it comes to Salesforce development, there are various tools and techniques that can help make the development process more efficient. One such technique is using an Apex method to get the ISO code by country name. By using an Apex method, you can quickly and easily obtain the required ISO code based on the country name.
An ISO code is an international standard used to identify a specific country, region, province, or language. For example, each country in the world is assigned a unique ISO code, such as the United States (USA
Salesforce Apex provides developers with the ability to retrieve ISO Code information for specific countries. This is useful for international applications where a user’s country or language needs to be stored. To prevent confusion, ISO Codes are often used in such cases.
There are several ways to create an Apex method to retrieve an ISO Code. Let’s see one of them.
If you want to get the ISO code by country name, see this post
public static String getIsoCodeByCountryName(String countryName) {
if (countryName == null) return null;
Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> pickListValues = fieldResult.getPicklistValues();
for (Schema.PicklistEntry pickListEntry : pickListValues) {
// pickListEntry.getLabel() returns the country name
// pickListEntry.getValue() returns the country code
if (pickListEntry.getLabel().toLowerCase() == countryName.toLowerCase()) {
return pickListEntry.getValue();
}
}
return null;
}
How to test the Apex method getIsoCodeByCountryName
@isTest static void testGetIsoCodeByCountryNameDynamic() {
// given
List<String> countries = getCountries();
for(String country :countries){
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode != null);
}
}
@isTest static void testGetIsoCodeByCountryNameInvalid() {
// given
String country = 'invalid country';
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode == null);
}
@isTest static void testGetIsoCodeByCountryNameNull() {
// given
String country = null;
// when
String isoCode = getIsoCodeByCountryName(country);
// then
System.assert(isoCode == null);
}
See that one of our test cases uses one aux method called getCountries to get all the countries available in the your Salesforce instance
public static List<String> getCountries(){
Schema.sObjectType objType = Contact.getSObjectType();
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
list<Schema.PicklistEntry> values = fieldMap.get('MailingCountryCode').getDescribe().getPickListValues();
List<String> countries = new List<String>();
for (Schema.PicklistEntry v : values){
countries.add(v.getLabel());
}
return countries;
}
You can get the Visualforce usage statistics from the VisualforceAccessMetrics object in Salesforce by using SOQL (Salesforce Object Query Language) to query the object and retrieve the desired information. Here’s an example of how you can do this:
SELECT ApexPageId, MetricsDate, TotalTime, AverageTime, TotalRequests, UniqueUsers
FROM VisualforceAccessMetrics
WHERE MetricsDate = TODAY
This query retrieves the Visualforce page ID, date, total time, average time, total requests, and unique users for the current day. You can modify the query to retrieve data for a different time period by changing the value in the WHERE clause.
Once you have executed the query, you can use the results to get the desired statistics and usage information for your Visualforce pages.
As a Salesforce administrator or developer, you may need to download a ContentVersion file through the Salesforce REST API using Curl. In this post, we’ll show you how to download the file with Curl in a few simple steps.
First, you’ll need to execute a query and extract the Content Version File ID. To do this, you can use Workbench or the REST explorer and issue a query like this:
SELECT Id, VersionData
FROM ContentVersion
WHERE Title = 'titleOfFile'
Or
SELECT Title, VersionData
FROM ContentVersion
WHERE Id = '0684V00000Qhf3mABB'
To download a ContentVersion file in Salesforce through the REST API, you’ll need to make a GET request to this endpoint:
Where <strong>XX</strong> is the Salesforce API version you’re using (e.g. 56 for API version 56), and recordId is the unique identifier of the ContentVersion record you want to retrieve.
Note that you’ll need to replace the following placeholder values:
<ACCESS_TOKEN>: with a valid Salesforce access token.
<instance>: with your Salesforce instance name (e.g. na1, eu0, etc.).
XX: with the Salesforce API version you’re using.
{recordId}: with the unique identifier of the ContentVersion record you want to retrieve.
Also, note that you’ll need to set the Content-Type header to application/octet-stream to indicate that you’re downloading a binary file.
In the response, the binary data of the ContentVersion file will be included in the body. You can write this data to a file on your local machine to save it.
In Salesforce, you can query accounts with at least one closed won opportunity by using a SOQL (Salesforce Object Query Language) query. Here’s an example of how you could write this query:
SELECT Id, Name, (SELECT Id, Name, StageName
FROM Opportunities
WHERE StageName='Closed Won')
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity
WHERE StageName='Closed Won')
LIMIT 10
This query returns all accounts that have at least one opportunity in the “Closed Won” stage. The inner query (SELECT Id, Name, StageName FROM Opportunities WHERE StageName='Closed Won') retrieves the closed won opportunities associated with each account, and the outer query (SELECT Id, Name, (...) FROM Account WHERE Id IN (...)) retrieves the account information for accounts with at least one closed won opportunity.
You can use this query in a number of different ways, such as in the Salesforce Developer Console, in Apex code, or in a tool such as the Workbench. Once you have the results, you can use them for further analysis, reporting, or to perform additional actions.
Salesforce is one of the most popular enterprise software solutions on the market. It’s a customer relationship management (CRM) system that helps companies large and small to build relationships with customers, manage sales operations, and create customer experiences. Salesforce enables businesses to capture and maintain customers’ data and track the history of interactions between representatives and customers. With its numerous features, Salesforce provides an optimal user experience, delivering insights and ensuring collaboration between multiple stakeholders.
Salesforce offers an array of products and services related to customer relationship management, marketing automation, analytics and app development. With these tools companies can quickly create cloud-based applications and customer relationship management portals, such as order status, company portals and customer service. Salesforce products and services offer businesses the opportunity to connect with their customers and analyse campaigns for customer engagement.
Salesforce provides businesses with a suite of cloud-based applications to manage sales, customer service, marketing, and commerce. The platform is designed to help businesses better understand and manage their customer interactions and data throughout the customer lifecycle, with the goal of improving business relationships and driving sales growth. Salesforce provides tools to manage sales and customer data, automate marketing and sales processes, and create custom mobile and web applications. Additionally, Salesforce offers a platform for developing custom integrations and extensions, allowing businesses to customize the platform to meet their unique needs.
Companies acquired by Salesforce
Probably some of the products acquired by Salesforce you already use daily and you didn’t know that are part of the Salesforce ecosystem
Slack
Mulesoft
Heroku
Quip
Tableau
Vlocity
Should I use salesforce in my company?
Whether or not you should use Salesforce in your company depends on a number of factors, including the size and nature of your business, your specific business needs, and your budget. Here are a few factors to consider:
Size of your business: Salesforce is designed for large enterprises and can be a good fit for companies with hundreds or thousands of employees. However, it can also be used by small businesses with a more limited number of employees.
Type of business: Salesforce is widely used by businesses in a variety of industries, including technology, finance, healthcare, and retail. If your business is focused on sales and customer relationship management, then Salesforce might be a good fit.
Business needs: Salesforce offers a wide range of tools and features to help businesses manage their customer interactions and data, including sales automation, customer service, marketing automation, and commerce. If your business has a need for these types of tools, then Salesforce might be a good fit.
Budget: Salesforce can be an expensive solution, and costs can quickly add up depending on the number of users, the specific features and tools you need, and any customization or integration requirements. It’s important to consider the overall cost and return on investment before making a decision.
Ultimately, the best way to determine if Salesforce is a good fit for your company is to assess your business needs, explore the platform and its features, and consider the costs and benefits. It might also be helpful to consult with a Salesforce expert or partner to get a better understanding of how the platform can help your business.
Configuring the Salesforce CLI (Command Line Interface) on Mac can seem like a tedious task. However, it doesn’t have to be! There are simple steps you can follow to ensure that your Salesforce CLI is configured correctly for Mac. This post will outline the steps needed to successfully configure the Salesforce CLI on Mac.
The Salesforce CLI is a powerful tool that helps you develop, customize, and enhance your Salesforce applications. The CLI offers several commands that can be used to create, configure, update, deploy, and delete metadata components. The Salesforce CLI can be used on both Windows and Mac operating systems.
This guide will walk you through the steps you need to take to configure the Salesforce CLI for Mac.
You can ask for help on an specific command. For example, let’s ask how auth command works:
$ sfdx auth --help
Authenticate the Salesforce CLI.
$ sfdx auth
Select:
$ auth web login
Follow the OAuth steps. This will open a browser window from which you can log in. Once you’re done, you can use the. rest of the commands available in the SFDX CLI tool.
Once the authentication is done, you can close the tab and go to the command line to see:
$ Successfully authorized my@username.dev with org ID 00A9V000001wCajUAB
To start downloading metadata c reate Salesforce DX project in your local machine:
Configure Visual Studio Code to use Salesforce CLI
There are several Visual Studio Code plugins available to make it easier to use Salesforce CLI in your development process. You can install these plugins and configure them to use your Salesforce org.
Downloading a file from Salesforce using Java is not as difficult as it may seem. With the right tools and knowledge, you can quickly and easily download any type of file from Salesforce via a Rest API. To get started, you’ll need a few software tools and a few lines of code.
Let say we want to download a file stored in Salesforce. Have in mind we said a File and not an Attachment (the old way to deal with files in Salesforce), so we’ll have to deal with ContentDocument, ContentVersion, ContentDocumentLink, etc.
Agenda:
Salesforce security token
Partner API
Salesforce Rest API
Store a file
Implementation
We are going to use force-partner-api dependency to get a session id after login
If we use Maven, our pom.xml will have this dependency
Let’s have some constants to keep our params in one place.
private static final Logger LOG = Logger.getLogger(Main.class.getName());
private static final String USERNAME = "********";
private static final String ACCESS_TOKEN = "********";
private static final String PASSWORD = "********"+ACCESS_TOKEN;
private static final String INSTANCE_URL = "https://********-dev-ed.my.salesforce.com";
private static final String API_VERSION = "51.0";
private static final String SALESFORCE_FILE_ID = "0684W00000AzWoiQAF"; // ContentVersion id
private static final String LOCAL_FILE_FULL_NAME = ""/tmp/sf-java.png"";
Important: the ACCESS_TOKEN constant represents the Salesforce security token you get from Settings -> Reset My Security Token
When you access Salesforce from an IP address that isn’t trusted for your company, and you use a desktop client or the API, you need a security token to log in. What’s a security token? It’s a case-sensitive alphanumeric code that’s tied to your password. Whenever your password is reset, your security token is also reset.
After you reset your token, you can’t use your old token in API applications and desktop clients.
The method to get the file (download and save it in our local disk)
private static void getFile(String sessionId) throws Exception {
String urlString = INSTANCE_URL+"/services/data/v"+API_VERSION+"/sobjects/ContentVersion/"+SALESFORCE_FILE_ID+"/VersionData";
LOG.info(urlString);
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/octet-stream");
con.setRequestProperty("Authorization", "OAuth "+sessionId);
LOG.info("Status "+con.getResponseCode());
LOG.info("Status message "+con.getResponseMessage());
// store the file in our disk
Files.copy(con.getInputStream(), Paths.get(LOCAL_FILE_FULL_NAME) , StandardCopyOption.REPLACE_EXISTING);
}
Are you looking to add a bit of personality and flair to your lightning data table? Conditional cell color gives designers and developers the opportunity to transform their table into something unique and eye-catching.
With conditional cell color, you are able to control the color of a cell and its contents based on the value of a particular item in the table. This means that each cell in a row can have its own distinct color, letting you highlight important information, emphasize data, and make the table look more visually appealing.
Expected result
Salesforce Lightning is a component-based framework for building user interfaces on the Salesforce platform. It provides a modern and efficient way for developers to create and deploy custom user interfaces that can run on any device, including desktops, laptops, tablets, and smartphones.
A Lightning Component is a reusable unit of code that implements a specific feature or functionality. Components can be composed into larger applications and can be easily reused and customized to meet different business needs. They are written in Aura, a proprietary JavaScript-based language, and use the Lightning Data Service to communicate with the Salesforce server.
Lightning Components provide a number of benefits, including faster performance, improved user experience, and greater customization options compared to traditional Salesforce user interfaces. They are an essential part of the Salesforce Lightning platform and are widely used by organizations to build custom applications and extend the functionality of the Salesforce platform.
Lightning data tables allow users to customize the colors of cells in a table based on the values of the cell using conditional formatting. This is a powerful tool for quickly identifying trends and outliers in data sets. With Lightning data tables, Salesforce developers can set color thresholds to automatically color cells according to whether their value is above/below a certain value or between two values. This feature is especially useful for displaying numerical values such as sales data, which often need to be highlighted at a glance so that users can quickly identify areas for improvement.
Let say you want to highlight a cell in a Lightning data table (lightning:datatable) when a specific value is invalid. In our example, we want to display those invalid emails in red.