Salesforce Implementation Guide How to implement Salesforce CRM? No matter how big or small your company—or the Salesforce CRM project—success requires planning, commitment, and strong sponsorship from your company’s executive team. It’s also critical that …
In this article, I will cover a step by step guide for using Salesforce Command Line Interface Data Loader: So first of all what is Command Line Interface Data Loader, and why should we use it …
Get Record Id in Lightning Component Get Record Id in Lightning Component using force:hasRecordId Getting current record id in lightning component or lightning aura component is very easy. We need to add force:hasRecordId interface to …
Salesforce Developer Interview Questions Salesforce developer interview questions and answers Here is list of all Salesforce developer interview questions: What is Salesforce? What is Cloud computing? What is CRM? What is PaaS? What is SaaS? …
Apex Triggers in Salesforce Apex Triggers in Salesforce What is Triggers in Salesforce? A trigger is an Apex script that executes before or after data manipulation language (DML) events occur. Apex triggers enable you to …
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;
}
}
Sometime there is requirement to display custom picklist field in visualforce page. If we have a picklist field then it can be displayed using inputfield tag easily. But if we want to display a custom values in picklist, It can not be done using inputfield tag. We can display custom picklist using ‘selectList’ tag in visualforce. We can display values or options for custom picklist using ‘selectOption’ or ‘selectOptions’ tag.
In the example below, we are showing two custom picklist. In first picklist we are using selectList with selectOption. We are showing list of countries using selectOption. In second picklist we are using selectList with selectOptions to display list of countries. We are setting selectOption list using apex code. We are setting list manually in Apex code, we can also set list dynamically using SOQL query and apex code in controller. In the example below, select value in both picklist and then click on save button. Then, selected picklist value will be shown in page.
Normally we use Apex data loader to import data in salesforce from CSV file. Now a days some other tools are also available to load data in salesforce like Jitterbit data loader. But sometime there is requirement when end users do not want to use Apex Data loader. They want some custom page to load data in salesforce. Then in that case we can use custom code to load data in salesforce from csv file.
Also sometime using single CSV file we want to load data in multiple objects. Then in that case we can not use data loader to load data. In that case we can use custom code to load data in salesforce.
In the example below we are loading data from CSV file for account objects.
First of all we need CSV file format. Click here to download CSV file. You can modify CSV file to insert or import account records. CSV file attached has following format:
Now we need to write code in Apex and visualforce which will read csv file and insert records in account object.
Click on choose file, then select csv file and then click on ‘Import Account’ button. All records from csv file will be inserted on account records. I have commented insert account line. So this example will only show account records on visualforce page. You can uncomment insert account list line in below code if you want to insert account list.
As we all know, there is one great saying ‘There are no shortcuts for success’. But here are some shortcuts that can really help you getting success. Yes, I am talking about Force.com IDE shortcuts. Each and every developer should use these shortcuts as these save our significant amount of time that we usually waste and don’t realize.
Here are some of them:
Use CTRL+SHIFT+R, to open the file from package explorer quickly. Would be better if you use ‘*’ in your search strings.
Use CTRL+H to search the files.
Use CTRL+L to navigate to the desired line number. This is extremely useful when your code contains thousands of number of lines.
Use CTRL+D to delete the entire line.
Use F12 to quickly activate the editor.
Use CTRL+K to find the next occurrence of the selected text. You can select a text or any word and press CTRL+K to find the next occurrence of the same text in that file.
Use CTRL+F6 to switch to the next editor.
Open the file -> Right Click -> Compare With -> Local History -> Select the Revision Time -> it will open a comparison window.
Use CTRL+SPACE, for the code context assistance. This is the most common and I think most of eclipse users are aware of this shortcut.
Use CTRL+W to close the current window/editor.
Use ALT+F7 to open the sub tab in the editor like Metadata and Source.
Use ALT+/ to show the correct variable name (type some letters and use this key).
Use CTRL+SHIFT+L to get the context menu help for all the available keyword shortcuts.
We should make our habit of using these shortcuts. These are very helpful and time saving. It will take only a few days to make it a habit and it can benefit you across your career.
Now a days, at many websites, you must have seen that there is an option to login using your facebook credentials. Similar is the case here where you want to log-in to your salesforce org using facebook credentials. So, here are the steps that will help you achieve the same.
For achieving the functionality, there should be a link between facebook and salesforce org. That’s why we need to give some information to facebook about our salesforce org and some information about facebook to our salesforce org. You can get started with the below steps:
Setting up a Facebook Application
First of all create a facebook app. Enter a display name of your choice. Namespace is optional. You can choose any option of your choice from category picklist.You can log in to your facebook profile and go to settings –> Create App —> Apps —> Create a New App
It will ask you to fill Captcha details as shown in the screenshot below:
After you submit this page, it will take you to the following screen.
Just click on show button to get the App ID and App Secret as both are needed by Salesforce to create a link. When you will click on Show button it will ask for your facebook password. Provide the same and get the App Secret.
Defining a Facebook Provider in your Salesforce Organization
Now, go to your salesforce Org and Go to Security Controls ——> Auth. Providers.
Click New.
In Provider Type picklist, select ‘Facebook’.
Enter a Name for the provider.(It can be any name of your choice)
Enter the URL Suffix. This is used in the client configuration URLs. For example, if the URL suffix of your provider is “MyFacebookProvider”, your single sign-on URL is similar to: https://login.salesforce.com/auth/sso/00Dx00000000001/MyFacebookProvider.
Use the Application ID from Facebook for the Consumer Key field.
Use the Application Secret from Facebook for the Consumer Secret field.
Custom Error URL is optional (not required).
Then, click ‘Automatically create a registration handler template’. It will create a new class in your salesforce org that will handle the registration of new users to your salesforce org or updation of any existing user in your org.
The class automatically generated needs some modification. you can use below code in your class.At line number 23 of the below code I have used profile id with which you want to create a new user. So Please replace that Id with the Id of some profile available in your respective salesforce org.
//TODO:This autogenerated class includes the basics for a Registration
//Handler class. You will need to customize it to ensure it meets your needs and
//the data provided by the third party.
global class AutocreatedRegHandler1380796002690 implements Auth.RegistrationHandler{
global boolean canCreateUser(Auth.UserData data) {
//TODO: Check whether we want to allow creation of a user with this data
// Set s = new Set{'usernamea', 'usernameb', 'usernamec'};
//if(s.contains(data.username)) {
//return true;
//}
return true;
}
global User createUser(Id portalId, Auth.UserData data){
if(!canCreateUser(data)) {
//Returning null or throwing an exception fails the SSO flow
return null;
}
//The user is authorized, so create their Salesforce user
User u = new User();
Profile p = [SELECT Id FROM profile WHERE id='00e90000001C3vh'];
//TODO: Customize the username. Also check that the username doesn't already exist and
//possibly ensure there are enough org licenses to create a user. Must be 80 characters
//or less.
u.username = data.username + '@myorg.com';
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
String alias = data.username;
//Alias must be 8 characters or less
if(alias.length() > 8) {
alias = alias.substring(0, 8);
}
u.alias = alias;
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = 'America/Los_Angeles';
u.profileId = p.Id;
insert u;
return u;
}
global void updateUser(Id userId, Id portalId, Auth.UserData data){
User u = new User(id=userId);
//TODO: Customize the username. Must be 80 characters or less.
//u.username = data.username + '@myorg.com';
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
//String alias = data.username;
//Alias must be 8 characters or less
//if(alias.length() > 8) {
//alias = alias.substring(0, 8);
//}
//u.alias = alias;
//update(u);
}
}
Select any user that has ‘Manage users’ permission in ‘Execute Registration As’ lookup field. The class created in above step will be called as this selected user.
When you will click Save, it will give you four URLs.
Updating Your Facebook Application
Go back to your facebook application you just created in last steps. Click on Settings in left option bar.
Click on +Add Platform and choose ‘Website’.
In Site URL, paste the callback URL provided by salesforce in previous steps and click Save Changes.
Testing the Single Sign-On Connection
First of all Logout from facebook, then in a browser, open the Test-Only Initialization URL on the Auth. Provider detail page of Salesforce. It should redirect you to Facebook and ask you to sign in. Upon doing so, you are asked to authorize your application. After you authorize, you are redirected back to Salesforce.
Then if it is successful then you can use the single sign on URL to test the same, and it will work the same way. It will ask for your facebook creds and then will create a new user with your username in salesforce(if not already there) and log you in to salesforce. This user registration thing is handled by the class that you have modified in above steps. So, if you face any problem then you can check your class code to resolve any issue.
Then you can single sign on URL to be provided anywhere on any website and it will prompt user to log-in with their facebook creds.
Many times we run into an issue of number of licenses. Our class tries to create a new user but because licenses are not available for the profile that we have set in our code, the new user is not created and it throws an error. Hence, if possible and suitable, you can use id of chatter profile(line no 23 of above code) as we have 5000 licenses for this profile.
A field set is a grouping of fields for same object. We can use dynamic bindings to display field sets on our Visualforce pages. Fieldset is very useful when we are working with managed package.
If we are using standard controller, then using fieldset in visualforce is straight forward. You can view my previous post for using fieldset in visualforce pages.
But if we are using custom controller or extension, then we may need to query fieldset fields in SOQL query. So we will use dynamic SOQL query for querying all fields of fieldset.
By using dynamic SOQL query in Apex and using fielset in visualforce and Apex code. Our code will become dynamic, then we can add, remover or reorder fields in fieldset. By doing so, our code will become dynamic. There is no need to modify code when we will do any change in fieldset.
In the example below, we will use fieldset to display account list on visualforce page. We will use dynamic SOQL query in Apex code.
First we need to create a fieldset. Go to Setup > Customize > Accounts > Field Set
Click on new. Enter all mandatory fields. Also drag and drop all required fields in fieldset.
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