Use static resource in Visualforce – Salesforce Force.com platform provides us a facility to upload, manage and use the content that is static (not changing) for your organization, and it can be stored under “Static …
Salesforce Winter ’21 Release Notes All you need to know about Salesforce Winter ’21 Release Notes Salesforce Winter ’21 Release Notes: We understand that it is difficult and a bit time-consuming to go through the entire …
Use Lightning Components in Visualforce Pages Use Lightning Components in Visualforce Pages How To Display Lightning Component In Visualforce Page In this post, we will see how we can use Lightning Components in Visualforce Pages …
Introducing Playground – Share and Collaborate Salesforce Solutions Are you a Salesforce developer or an administrator working on a development task? Did you just spend writing a block of code again that you wrote …
Lightning Spinner in LWC (Lightning Web Component) What is Lightning Spinner in LWC? Lightning Spinners are CSS loading indicators that should be shown when retrieving data or performing slow computations. lightning-spinner displays an animated spinner …
apexpages.currentpage().getparameters().get(‘id’) can be used to get current record id or other url parameters in apex code.
Many times we have requirement to get current record id or url parameters of visualforce page in apex code.
Many times we require the current record id in controller. For example we are redirecting from one visualforce page to another visualforce page using apex code and we have also set some parameters for second visualforce page. Then, in that case we can use apexpages.currentpage().getparameters().get(‘id’) to get parameter with id name or any other name.
One more example if we have a button on detail page overridden by visualforce page and once the button is pressed you require the id(or the other field values of that record) of the record from whose detail page the button was clicked. For this requirement also we can use ApexPages.CurrentPage().getparameters().get(‘id’) to get other parameters.
In the following example we will use a custom extension to get current record id and one parameter with name nameParam. Then we are using one visualforce page to display current record id and all fields related to that record id by querying using SOQL query and also displaying value of one more parameter with name nameParam. In this way we can get value of any parameter in Apex code.
<apex:page standardController="Account" extensions="CurrentRecordIdDemoController">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Current account record Id is : {!currentRecordId}" collapsible="false">
<apex:outputField value="{!acc.name}"/>
<apex:outputField value="{!acc.AccountNumber}"/>
<apex:outputField value="{!acc.Type}"/>
<apex:outputField value="{!acc.Industry}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Testing parameter" collapsible="false">
Name is <b>{!parameterValue}</b>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Code:
public class CurrentRecordIdDemoController{
public String currentRecordId {get;set;}
public String parameterValue {get;set;}
public Account acc{get;set;}
public CurrentRecordIdDemoController(ApexPages.StandardController controller) {
currentRecordId = ApexPages.CurrentPage().getparameters().get('id');
acc = [select id ,name, AccountNumber, Type, Industry from Account where id =: currentRecordId ];
parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
}
}
Force.com migration tool(based on JAVA), is used to deploy the Metadata from one organization to other organization or we can use it to retrieve the metadata from one organization and then make some changes locally and then deploy that metadata again to the same organization. We can also migrate the metadata using Change sets but there are some extra features provided in this ANT migration tool:
The main advantage of this tool is, that it gets the metadata in form of XML files from your server and downloads it locally on your computer. Thus you can make changes in those XML files locally and again deploy the changes to any server instance, any target org that you want.
It allows you to deploy the same metadata any number of times to any of your server, as you have downloaded the metadata in form of XML files, you can deploy them again and again.
Change set does not allow you to delete any metadata component from target org. But using ANT migration tool you can delete the components from target org. This is done using destructiveChanges.xml file.
Some components are not supported to be migrated using change sets but you can migrate them using ANT migration tool.
It can also be run from command prompt using some specific commands for calling APIs.
You can also automate your migration process leveraging the capabilities of command prompt .bat files and XML structure of source files.
This tool works with the help of some XML files that we create in order to use this tool. In those XML files, we provide information about our server ( like credentials, login URL, and some other attributes as well) , information about the operation that we want to perform (these are called targets, like retrieve or deploy, file is build.xml), then information about the components that you want to retrieve or deploy(package.xml).
Below is one basic example. Here we will first retrieve the components from source org and then will deploy those components to the target org. Here is the folder that we have initially. We have build.xml and build.properties file here and one folder named “unpackaged” in which we have our package.xml. This package.xml file contains the list of components to be retrieved from source org.
Folder Structure ANT Migration
Below are the details of each file that we have in the current folder structure.
Build.properties : We provide the information about our instance on which we want to perform the operation (deploy or retrieve or any other possible operation). Below is the sample. Here in this file we have only enabled the username and password for source org as we will first retrieve the components from source org and build.xml file will use these credentials. But while deploying those components to target org , we’ll have to changes these credentials info to target org’s credentials, so that in the next target that we run from command prompt to deploy the components, the build.xml file will use the target org’s credentials for deployment of components.This is the file that is referred in the next file which is build.xml. All the lines in the below code that starts with # are considered as comments.
# build.properties
# Specify the login credentials for the desired Salesforce organization, and if you have IP restrictions then you have to append your security token with the password.
sf.username = sourceorguser@abc.com
sf.password = testuser123
#sf.pkgName = Insert comma separated package names to be retrieved
# Use 'https://login.salesforce.com' for production or developer edition (the default if not specified).
# Use 'https://test.salesforce.com for sandbox.
sf.serverurl = https://login.salesforce.com
sf.maxPoll = 20
# If your network requires an HTTP proxy, see http://ant.apache.org/manual/proxy.html for configuration.
Build.xml : Here we provide the actions or we can say the operation that we want to perform ( either retrive or deploy or any other possible operation). These tags are called targets also. So, user can run these targets one by one and complete the task in sequential manner as he/she wants. In the below example we have one retrieve target and one deploy target. Every target has some name which we’ll use when calling these targets from command prompt. This file refers build.properties file where we have mentioned all the info required in this file(like username, password, serverurl)
<project name="Sample usage of Salesforce Ant tasks" default="test" basedir="." xmlns:sf="antlib:com.salesforce">
<property file="build.properties"/>
<property environment="env"/>
<!-- Retrieve an unpackaged set of metadata from your org -->
<!-- The file unpackaged/package.xml lists what is to be retrieved -->
<target name="retrieveUnpackaged">
<!-- The below tag creates a new folder in your directory structure, if the folder with the same name does not exist, otherwise uses the previous folder itself -->
<mkdir dir="retrieveUnpackaged"/>
<!-- sf:retrieve retrieves the contents into another directory. we refer the username, password, serverurl, maxPoll from build.properties file that is present -->
<!-- In "retrieveTarget" attribute we mention the path of the folder where we want to retrieve the components -->
<!-- In "unpackaged" attribute we mention the path of the folder where we have the package.xml file that contains the name of the components to be retrieved -->
<sf:retrieve username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" maxPoll="${sf.maxPoll}" retrieveTarget="retrieveUnpackaged" unpackaged="unpackaged/package.xml"/>
</target>
<!-- Deploy the unpackaged set of metadata retrieved with retrieveUnpackaged -->
<target name="deployUnpackaged">
<sf:deploy username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" maxPoll="${sf.maxPoll}" deployRoot="retrieveUnpackaged"/>
</project>
Package.xml : This is the last xml file that we need. We have to mention the API name of components that we want to retrieve from source org. And the same xml can be used while deploying those components to target org.
After we have all these three files ready, we need to go to the command prompt and go to the same folder location where we have the folder structure as shown above ( where we have build.xml file).
Run the command ant retrieveUnpackaged on the command prompt.
This has to be the name of the target that you want to run. So in the first step we have run a retrieve command in retrieveUnpackaged target. After successfully running this target our directory structure will be like below. As in the target we ran right now, we mentioned that system should create new folder with the name retrieveUnpackaged that will contain all the retrieved components with the corresponding package.xml file as well.
Folder Structure after retrieve
Now we have all the components retrieved in the retrieveUnpackaged folder. Now we just need to run another target in our build.xml target that issues a deploy command.
Before running the below command you should modify your build.properties file to contain the username and password of the target org.
Run the command ant deployUnpackaged on the command prompt. You will end up deploying all the components present in the folder retrieveUnpackaged to the target org.
Before starting using migration tool, you need to do some set-up on your machine in order to get the commands
executed from command prompt. So, first of all you need to install the JAVA and Force.com migration tool on your system. Below are the steps to have these things done:
Extract the downloaded zip file somewhere like C:\apache-ant-1.9.4-bin\apache-ant-1.9.4
Set this path in system variables as ANT_HOME.
If PATH system variable already exists then add %ANT_HOME% to your path variable, else add new PATH variable and keep this value.
Also create a JAVA_HOME environment variable and set the value to the location of your JDK.
Go to command prompt and type ant -v. If it shows that ‘Apache Ant Version compiled’ then that means we are good to go.
Till here you have downloaded and configured the required steps for ANT. Now you have to download the Force.com migration tool from your salesforce org ( it can be any org ). Go to Your Name > Setup > Develop > Tools.
Click the “Force.com Migration Tool” link to download a zip file. Inside this zip file you can find the ant-salesforce.jar file and some sample configuration files.
Copy the jar file mentioned above and paste it into the lib folder of your ant installation direcotry ‘C:\apache-ant-1.9.4-bin\apache-ant-1.9.4\lib‘.
Now, you are ready to use ANT with force.com migration tool. You can now deploy or retrieve your salesforce.com Metadata using ANT and command prompt.
actionStatus visualforce component displays the status of an AJAX update request. An AJAX request can either be in progress or complete.
Depending upon the AJAX request status (whether AJAX request is in progress or complete), this component will display different message to user. In many scenarios AJAX request takes some time. So we should display some message to user that your request is in progress. Once request is complete, we can display some different message to user.
Using actionstatus, we can also display some gif (graphic Interchange Format), which shows to user that their request is in progress. It gives very good presentation to end user.
In the example below, we are using actionStatus for commandbutton. We are showing account edit page to user. When user will click on save buttton, request will go to controller method. We are showing gif image to user while AJAX request is in progress using actionstatus component. We are using apex:facet tag inside actionstatus to show image and we have specified name value as ‘start’ in apex:facet tag. So It will show image when request is in progress. We can also use ‘stop’ value in name attribute of apex:facet to specify message when request completes.
public class actionStatusImage {
public Account account{get;set;}
public actionStatusImage(){
account = new Account();
}
public Pagereference save(){
//upsert account;
return null;
}
}
We can use System.Label.labelName to access custom label in apex code.
Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.
To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName
Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.
After creating custom label we can use following code to use custom label in apex code.
Visualforce Page:
<apex:page controller="CustomLabelApexDemoController">
<apex:form >
<apex:pageblock >
Value stored in custom label is: <b>{!customLabelValue}</b>
</apex:pageblock>
</apex:form>
</apex:page>
public class CustomLabelApexDemoController {
public string customLabelValue{get;set;}
public CustomLabelApexDemoController(){
customLabelValue = System.Label.DemoLabel;
}
}
If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom apex code which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in apex code.
We can use $Label global variable to access custom label in visualforce page.
Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.
To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in visualforce page using $Label global variable.
Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.
After creating custom label we can use following code to use custom label in visualforce page
If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom visualforce page which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in Visualforce page.
Many times I have seen question from others that how can we write trigger on attachment in salesforce. For the Attachment, ContentDocument and Note standard objects, we can’t create a trigger in the Salesforce user interface. For these objects, we can create a trigger using development tools, such as the Developer Console or the Force.com IDE. Alternatively, we can also use the Metadata API.
In this example we will learn to write trigger on attachment object in salesforce. Firstly I will explain using developer console. Here are steps to create trigger on attachment using developer console.
1. Click on your name at (top left corner) and Select “Developer Console”
2. Go to File -> New -> Apex Trigger.
3. Select name of SObject and enter name of trigger
4. Click on submit button. In this way we can create trigger on attachment.
In similar way we can also create trigger using force.com IDE.
We should be very careful while writing the trigger on Attachment, as it will be used by all standard or custom Object on which attachment is added. We should provide criteria to run trigger so that trigger should be executed for required objects only.
In this example I will create the trigger which will check for the parent object “Account”. If the object is Account then it will update one field on account record.
Trigger Code:
trigger AttachmentTriggerDemo on Attachment (before insert) {
List accountList = new List();
Set accIds = new Set();
for(Attachment att : trigger.New){
//Check if added attachment is related to Account or not
if(att.ParentId.getSobjectType() == Account.SobjectType){
accIds.add(att.ParentId);
}
}
accountList = [select id, has_Attachment__c from Account where id in : accIds];
if(accountList!=null && accountList.size()>0){
for(Account acc : accountList){
acc.has_Attachment__c = true;
}
update accountList;
}
}
Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform text searches in records. Use SOSL to search fields across multiple standard and custom object records in Salesforce. SOSL is a search language in salesforce and the important feature is that Unlike SOQL, we can search in multiple objects at same time using SOSL. In SOQL, we can query only one object at a time but in SOSL, We can search for some specified string like ‘testString’ in multiple objects at the same time.
We can search for some specified string like ‘testString’ in multiple objects at the same time.
We can mention in which fields of all the sObjects,we want to search for the string specified.
The SOSL query start with the keyword ‘FIND’.
You can specify, which fields to return for each object mentioned in SOSL query. Suppose you have performed search on three objects Account, Contact & Opportunity. Then you can mention like, for list returned with Account results only (Name, Industry) fields should come, and for Contacts results (firstName, lastName) should come and similarly for Opportunity.
The result of SOSL is a list of lists of sObjects “List<List<sObject>>”.
The returned result contains the list of sObjects in the same order as order mentioned in SOSL query.
If a SOSL query does not return any records for a specified sObject type, then search results include an empty list for that sObject.
The search string should be at least two characters long.
Below is the sample code that has a input text box and a command button which will search for the entered string in three Object . i.e Accounts, Contacts, Opportunities and returned result will be shown in the page block tables.
Public with sharing class SOSLController{
Public List<Opportunity> optyList {get;set;}
Public List<contact> conList{get;set;}
Public List<account> accList{get;set;}
Public String searchStr{get;set;}
Public SOSLController(){
}
Public void soslDemo_method(){
optyList = New List<Opportunity>();
conList = New List<contact>();
accList = New List<account>();
if(searchStr.length() > 1){
String searchStr1 = '*'+searchStr+'*';
String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
List<List <sObject>> searchList = search.query(searchQuery);
accList = ((List<Account>)searchList[0]);
conList = ((List<contact>)searchList[1]);
optyList = ((List<Opportunity>)searchList[2]);
if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
return;
}
}
else{
apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least two characters..'));
return;
}
}
}
Difference between SOQL and SOSL
Like SOQL, SOSL allows you to search your organization’s records for specific information. Unlike SOQL, which can only query one standard or custom object at a time, a single SOSL query can search all objects.
Another difference is that SOSL matches fields based on a word match while SOQL performs an exact match by default (when not using wildcards). For example, searching for ‘Digital’ in SOSL returns records whose field values are ‘Digital’ or ‘The Digital Company’, but SOQL returns only records with field values of ‘Digital’.
SOQL and SOSL are two separate languages with different syntax. Each language has a distinct use case:
Use SOQL to retrieve records for a single object.
Use SOSL to search fields across multiple objects. SOSL queries can search most text fields on an object.
For more information and possibilities in SOSL, please refer trailhead
You can use SOQL in java-script on your VF pages or any kind of java-script that you write, like we can get it executed on click of a button or link present on your detail page of a record. Below is the simple example and you can use it and modify it accordingly :
Javascript code:
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
try{
var query = "SELECT Id,Name from Account LIMIT 2";
var records = sforce.connection.query(query);
var records1 = records.getArray('records');
alert(records);
var accountNames = '';
for(var i=0;i<records1.length;i++){
accountNames = accountNames + records1[i].Name + ',';
}
alert(accountNames);
if(records1.length == 1){
//window.location.href = 'http://www.google.com';
}
else{
alert('There is no Account');
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}
you need to use .js files that are in first two lines in order to use the api of salesforce to connect and fetch the records using SOQL. In the example you will see result of SOQL in alert statement. The result that is returned contains a ‘records’ named array component that can be used to iterate over and go through all the records and use it in the same manner as we do in usual apex program. For ex account.id, account.Name etc.
You can also use merge fields to create dynamic queries.
Similarly you can use javascript to create, update or delete the salesforce object’s records using API. Below is the sample code you can use to create a new account record in your org.
Javascript code:
try{
var accounts = [];
var account = new sforce.SObject("Account");
account.Name = "my new account Test";
accounts.push(account);
var results = sforce.connection.create(accounts);
if (results[0].getBoolean("success")) {
alert("new account created with id " + results[0].id);
} else {
alert("failed to create account " + results[0]);
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}
you just need to create a new button and fill the details as shown below in the screenshot:
Below this there would be a text box where you need to write your javascript code (provided above). After saving the button, you need to get it on your page layout and we are good to go.
Permanent link to this article: https://www.sfdcpoint.com/salesforce/soql-query-in-javascript-example/
Custom visualforce components are very useful. In our projects, many times we develop codes which are required again and again. So instead of repeating same code again and again, we can create visualforce component. Then we can use visualforce component in every place where we need that particular piece of code. In other words, custom visualforce component allows us to create reusable component.
All custom visualforce component definitions must be wrapped inside a single <apex:component > tag.
We can also use <apex:attribute> tag to use customize the component so that custom component can be used in different manners depending on value of different attributes. It helps us in creating reusable generic component and also saves time and number of lines we write in apex and visualforce page.
In the example below, we will learn to create very basic custom visualforce component.
First we will create visualforce component. Go to Setup -> Develop -> Components -> then write component name. In our case component name is ‘myComponent’.
Component Code:
<apex:component >
<apex:attribute name="textValue" description="This is the value for the component" type="String" required="true"/>
<apex:attribute name="textColor" description="This is color for the border." type="String" required="true"/>
<apex:outputText value="{!textValue}" style="color:{!textColor};"/>
</apex:component>
This component is creating two attributes using <apex:attribute> tag. First attribute is deciding what text text should be displayed and second attribute is deciding color of text. We can use any number of attribute in component. Component can also have controller which helps in more customizable component.
Now we need to use this component. We can use component in visualforce page using <c:componentName>.
Visualforce Code:
<apex:page tabStyle="Account">
<apex:pageBlock >
<apex:pageBlockSection title="myComponent Test" collapsible="false">
<c:myComponent textValue="This Text is blue" textColor="blue" />
<c:myComponent textValue="But this is red" textColor="red" />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
actionStatus visualforce component displays the status of an AJAX update request. An AJAX request can either be in progress or complete. It can be done using apex:actionStatus
Depending upon the AJAX request status (whether AJAX request is in progress or complete), this component will display different message to user. In many scenarios AJAX request takes some time. So we should display some message to user that your request is in progress. Once request is complete, we can display some different message to user.
Using actionstatus, we can also display some gif (graphic Interchange Format), which shows to user that their request is in progress. It gives very good presentation to end user.
In the example below, we are using actionStatus for commandbutton. We are showing account edit page to user. When user will click on save buttton, request will go to controller method. We are showing gif image to user while AJAX request is in progress using actionstatus component. We are using apex:facet tag inside actionstatus to show image and we have specified name value as ‘start’ in apex:facet tag. So It will show image when request is in progress. We can also use ‘stop’ value in name attribute of apex:facet to specify message when request completes.
public class actionStatusImage {
public Account account{get;set;}
public actionStatusImage(){
account = new Account();
}
public Pagereference save(){
//upsert account;
return null;
}
}
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. AcceptRead More
Privacy & Cookies Policy
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
Recent Comments