Jun 18

Trigger on Attachment in Salesforce

Trigger on Attachment in Salesforce

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”

developer console

2. Go to File -> New -> Apex Trigger.

Debeloper Console 2

3. Select name of SObject and enter name of trigger

developer console3

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;
    }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/trigger-on-attachment-in-salesforce/

May 04

SOSL Example in Salesforce

SOSL Example in Salesforce


SOSL – Salesforce Object Search Language

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 be returned, and for Contacts results (firstName, lastName) should be returned 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.

Here is the quick demo SOSL Demo

SOSL-Example-in-Salesforce

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.

<apex:page controller="SOSLController">
  <apex:form >
  <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslDemo_method}"                reRender="acct,error,oppt,cont" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
                <apex:facet name="start" >
                    <img src="/img/loading.gif"/>                    
                </apex:facet>
    </apex:actionStatus>
  </apex:form>

    <apex:outputPanel title="" id="error">
     <apex:pageMessages ></apex:pageMessages>
     </apex:outputPanel>

    <apex:pageBlock title="Accounts" id="acct">
    <apex:pageblockTable value="{!accList }" var="acc">
          <apex:column value="{!acc.name}"/>
          <apex:column value="{!acc.Type}"/>
       </apex:pageblockTable>
    </apex:pageBlock>

 <apex:pageBlock title="Contacts" id="cont">
    <apex:pageblockTable value="{!conList}" var="con">
      <apex:column value="{!con.name}"/>
      <apex:column value="{!con.email}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
 
 <apex:pageBlock title="Opportunities" id="oppt">
    <apex:pageblockTable value="{!optyList}" var="opty">
      <apex:column value="{!opty.name}"/>
     <apex:column value="{!opty.StageName}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
  
</apex:page>

Below is the controller for the same

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;
   }
  }
}

For more information and possibilities in SOSL, please Click Here

Permanent link to this article: http://www.sfdcpoint.com/salesforce/sosl-example-in-salesforce/

Apr 19

SOQL query in javascript example

SOQL query in javascript example

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:

SOQL in javascript example

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: http://www.sfdcpoint.com/salesforce/soql-query-in-javascript-example/

Apr 12

Custom Visualforce Component example

Custom Visualforce Component 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.

Click for Demo

Custom Visualforce Component example

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>

Permanent link to this article: http://www.sfdcpoint.com/salesforce/custom-visualforce-component-example/

Mar 31

actionstatus visualforce loading image

actionstatus visualforce loading image

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.

Click for Demo

actionstatus visualforce loading image

Visualforce Page:

<apex:page controller="actionStatusImage" tabStyle="Account">
    <apex:form id="formId">
    <apex:pageBlock id="pgBlckId" title="New Account">
        
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save" reRender="pgBlckId" status="actStatusId"/>
            <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
        </apex:pageBlockButtons>
        
        <apex:pageBlockSection id="pgBlckSecId" title="Account Information" collapsible="false">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.Phone}"/>
            <apex:inputField value="{!account.Type}"/>
            <apex:inputField value="{!account.Rating}"/>
            <apex:inputField value="{!account.Industry}"/>
            <apex:inputField value="{!account.site}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class actionStatusImage {
    public Account account{get;set;}
    public actionStatusImage(){
        account = new Account();
    }
    public Pagereference save(){
        //upsert account;
        return null;
    }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/actionstatus-visualforce-loading-image/

Mar 30

Custom Picklist in visualforce salesforce

Custom Picklist in visualforce salesforce

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.

Click for Demo

Custom Picklist in Visualforce Salesforce

 

Visualforce Page:

<apex:page controller="customPickListInVFDemoController" tabStyle="Account">
  <apex:form >
    <apex:pageBlock title="Custom PickList Demo" id="out">
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}" rerender="out" status="actStatusId"/>
            <apex:actionStatus id="actStatusId">
                <apex:facet name="start">
                    <img src="/img/loading.gif" />
                </apex:facet>
            </apex:actionStatus>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="Custom Picklist Using selectList and selectOption" collapsible="false">
            <apex:selectList value="{!selectedCountry1}" multiselect="false" size="1">
                <apex:selectOption itemValue="INDIA" itemLabel="India"/>
                <apex:selectOption itemValue="USA" itemLabel="USA"/>
                <apex:selectOption itemValue="United Kingdom" itemLabel="UK"/>
            </apex:selectList>
            
            <apex:outputText value="{!selectedCountry1}" label="You have selected:"/>
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions" collapsible="false">
            <apex:selectList value="{!selectedCountry2}" multiselect="false" size="1">
                <apex:selectOptions value="{!countriesOptions}"/>
            </apex:selectList>
            
            <apex:outputText value="{!selectedCountry2}" label="You have selected:"/>
        </apex:pageBlockSection>
    </apex:pageblock>
  </apex:form>
</apex:page>

Apex Code:

public class customPickListInVFDemoController {
public String selectedCountry1{get;set;}
public String selectedCountry2{get;set;}
    public customPickListInVFDemoController(){
    }
    
    public List<SelectOption> getCountriesOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('INDIA','India'));
        countryOptions.add(new SelectOption('USA','USA'));
        countryOptions.add(new SelectOption('United Kingdom','UK'));
        countryOptions.add(new SelectOption('Germany','Germany'));
        countryOptions.add(new SelectOption('Ireland','Ireland'));

        return countryOptions;
    }
    public PageReference save(){
        return null;
    }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/custom-picklist-in-visualforce-salesforce/

Mar 02

Import csv file using apex visualforce

Import csv file using apex visualforce

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:

Import csv file using apex visualforce

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.

Click for demo

Import csv file using apex visualforce

Visualforce Page:

<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Apex Code:

public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
 
  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
           
           for(Integer i=1;i<csvFileLines.size();i++){
               Account accObj = new Account() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               acclist.add(accObj);   
           }
        //insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/import-csv-file-using-apex-visualforce/

Mar 01

Eclipse shortcuts for salesforce IDE

Eclipse shortcuts for salesforce IDE

Hi Friends,

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:

  1. Use CTRL+SHIFT+R, to open the file from package explorer quickly. Would be better if you use ‘*’ in your search strings.
  2. Use CTRL+H to search the files.
  3. Use CTRL+L to navigate to the desired line number. This is extremely useful when your code contains thousands of number of lines.
  4. Use CTRL+D to delete the entire line.
  5. Use F12 to quickly activate the editor.
  6. 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.
  7. Use CTRL+F6 to switch to the next editor.
  8. Open the file -> Right Click -> Compare With -> Local History -> Select the Revision Time -> it will open a comparison window.
  9. 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.
  10. Use CTRL+W to close the current window/editor.
  11. Use ALT+F7 to open the sub tab in the editor like Metadata and Source.
  12. Use ALT+/ to show the correct variable name (type some letters and use this key).
  13. 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.

Permanent link to this article: http://www.sfdcpoint.com/salesforce/eclipse-shortcuts-salesforce-ide/

Feb 26

Login to salesforce with facebook

Login to salesforce with facebook credentials

Hello everyone,

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

Facebook App

  • It will ask you to fill Captcha details as shown in the screenshot below:

Captcha

  • After you submit this page, it will take you to the following screen.

code

  • 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.

facebook app

  • Click on +Add Platform and choose ‘Website’.

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.

For more information visit Configuring a Facebook Authentication Provider

Permanent link to this article: http://www.sfdcpoint.com/salesforce/login-salesforce-with-facebook/

Feb 22

Fieldset apex code salesforce

Fieldset apex code salesforce

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.

Click for Demo

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.

Create account field set

Visualforce Page:

<apex:page controller="AccountFieldSetController" tabStyle="Account">
  <apex:form >
      <apex:pageblock >        
          <apex:pageBlockSection title="Account list" collapsible="false">
             <apex:pageBlockTable value="{!accList}" var="acc">
                 <apex:repeat value="{!$ObjectType.Account.fieldsets.accountFieldSet}" var="fieldValue">
                     <apex:column value="{!acc[fieldValue]}">
                     </apex:column>
                 </apex:repeat>
             </apex:pageBlockTable>
          </apex:pageBlockSection>
          
          <apex:pageBlockSection title="Account Dynamic query" collapsible="false">
              <apex:outputText value="Query is: {!queryString}" />
          </apex:pageBlockSection>
          
      </apex:pageblock>
    </apex:form>
</apex:page>

Apex Code:

public class AccountFieldSetController {
    public String queryString{get;set;}
    public List<Account> accList{get;set;}
    public AccountFieldSetController(){
        queryString = 'select id';
        for(Schema.FieldSetMember fld :SObjectType.Account.FieldSets.accountFieldSet.getFields()) {
         queryString += ', ' + fld.getFieldPath();
        }
        queryString += ' from Account limit 5';
        
        acclist = Database.query(queryString);
    }
    
}

We will get following output in visualforce page:

FieldSet Apex Code Salesforce Example

Permanent link to this article: http://www.sfdcpoint.com/salesforce/fieldset-apex-code-salesforce/