Passing sObjects to future methods in Salesforce

So how to pass sObject to future methods, even when we know that the future methods do not accept the sobjects. So how do we do it?
We will use the JSON methods to first serialize the list of account which will be serialized as string. This string is passed to the future method and then in the future method we will de-serialize the string back to list of account and insert the accounts.

Here’s the code;

This is the main class, we will call it GenerateJson

	public class GenerateJson{
    //Constructor
    public GenerateJson(){
        // I have hardcoded the name and the account number in Kannada!! 
        account acc1 = new account(name = 'ಬೆಂಗಳೂರು', AccountNumber= '೧೦೨೯೩೭');
        account acc2 = new account(name ='ಹುಬ್ಬಳ್ಳಿ', AccountNumber= '೬೮೬೮೮೮೦');
        
        //Initialize a list of account
        list<account> accList = new list<account>();
        accList.add(acc1);
        accList.add(acc2);
        
        //Using the JSON.serializePretty we will serialize the list of account.
        string jsonString = JSON.serializePretty(accList);

        //Pass the serialized list to the future method.
        DeserializeJsonRecords.insertAccount(jsonString);
    }
}       

We will create another class with a future method. We will name the class DeserializeJsonRecords

public class DeserializeJsonRecords{
    
    @future
    public static void insertAccount(string accountString){
        //Deserialize the list and cast it to account list.
        list<account> insertAccList =  (list<account>)JSON.deserializeStrict(accountString, list<account>.class);
		//Insert the accounts
        insert insertAccList;
    }
}

To check if the code works just run the below line in the developer console

GenerateJson genJson = new GenerateJson();

One of the catch here is if the size of the list is very huge then there are chances that the heap size limit will be reached. Also I am not sure about how the the rich text area fields are deserialized, will need to test that.

Hope it helps!

Generate a PDF and Attach it to record from a trigger in Salesforce — SOAP webservice

The reason you stumbled upon this post is because you tried using the .getContentAsPdf() method in a trigger and you got an error message stating you cannot use it in a trigger. So you tried to search and figure out as to how you could do it.

I had faced a similar issue when a task was given to me attach a pdf(which would be automatically created) when a record is created. Inititally I thought its quite simple and accepted it. But when I actually started coding, I became aware of the issues with this requirement.

Well, I googled for a while and came across a post (unfortunately, I could not find it now) which had the solution to this problem, but the guy had not posted the code to demonstrate. So I thought I could share the code in a post as this could help someone.

Here you go:
Step 1: create a class and include a webservice method that will generate the pdf and attach it to a record
Step 2: Generate the WSDL from this class.
Step 3: Generate a class from the WSDL you just created. (step 2 and 3 are a little wierd, but believe me it works)
Step 4: Create a class which has future Method (with callout=true). This future method will call the stub which you just created from the WSDL.
Step 5: Finally create a trigger that will call this future method.

If you find any better way of doing this please do let me know.

In this scenario I will create a account and a pdf will be attached to it after the insert.

First lets create the VF page to generate the pdf, a simple one. Lets call it, pdfRenderPage


<apex:page standardController="Account" renderAs="pdf">

Hey, the Account name is {!account.Name}

</apex:page>

The webservice class, After you save this class, you can see a generate WSDL button. click on it and save the WSDL file

global class AddPdfToRecord{

    webservice static void addPDF(list<id> accountIds){
		//Instantiate a list of attachment object
        list<attachment> insertAttachment = new list<attachment>();
        for(Id accId: accountIds){
			//create a pageReference instance of the VF page.
            pageReference pdf = Page.pdfRenderPage;
			//pass the Account Id parameter to the class.
            pdf.getParameters().put('id',accId);
            Attachment attach = new Attachment();
            Blob body;
            if(!test.isRunningTest()){
                body = pdf.getContent();
            }else{
                body=blob.valueOf('TestString');
            }
            attach.Body = body;
            attach.Name = 'pdfName'+accId+'.pdf';
            attach.IsPrivate = false;
            attach.ParentId = accId;//This is the record to which the pdf will be attached
            insertAttachment.add(attach);
         }
		 //insert the list
         insert insertAttachment;
    }
}

Now, consume the WSDL that you just generate. Go to Setup->App Setup-> Develop-> Apex Classes and click on Generate from WSDL. Load the WSDL file and name the class as ‘addPDFStub’.

//Generated by wsdl2apex

public class addPDFStub {
    public class LogInfo {
        public String category;
        public String level;
        private String[] category_type_info = new String[]{'category','http://soap.sforce.com/schemas/class/AddPdfToRecord','LogCategory','1','1','false'};
        private String[] level_type_info = new String[]{'level','http://soap.sforce.com/schemas/class/AddPdfToRecord','LogCategoryLevel','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'category','level'};
    }
    public class AllowFieldTruncationHeader_element {
        public Boolean allowFieldTruncation;
        private String[] allowFieldTruncation_type_info = new String[]{'allowFieldTruncation','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'allowFieldTruncation'};
    }
    public class DebuggingHeader_element {
        public addPDFStub.LogInfo[] categories;
        public String debugLevel;
        private String[] categories_type_info = new String[]{'categories','http://soap.sforce.com/schemas/class/AddPdfToRecord','LogInfo','0','-1','false'};
        private String[] debugLevel_type_info = new String[]{'debugLevel','http://soap.sforce.com/schemas/class/AddPdfToRecord','LogType','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'categories','debugLevel'};
    }
    public class CallOptions_element {
        public String client;
        private String[] client_type_info = new String[]{'client','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'client'};
    }
    public class SessionHeader_element {
        public String sessionId;
        private String[] sessionId_type_info = new String[]{'sessionId','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'sessionId'};
    }
    public class addPDFResponse_element {
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class DebuggingInfo_element {
        public String debugLog;
        private String[] debugLog_type_info = new String[]{'debugLog','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'debugLog'};
    }
    public class addPDF_element {
        public String[] accountIds;
        private String[] accountIds_type_info = new String[]{'accountIds','http://soap.sforce.com/schemas/class/AddPdfToRecord','ID','0','-1','true'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord','true','false'};
        private String[] field_order_type_info = new String[]{'accountIds'};
    }
    public class AddPdfToRecord {
        public String endpoint_x = 'https://'+URL.getSalesforceBaseUrl().getHost()+'/services/Soap/class/AddPdfToRecord';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public addPDFStub.CallOptions_element CallOptions;
        public addPDFStub.AllowFieldTruncationHeader_element AllowFieldTruncationHeader;
        public addPDFStub.SessionHeader_element SessionHeader;
        public addPDFStub.DebuggingHeader_element DebuggingHeader;
        public addPDFStub.DebuggingInfo_element DebuggingInfo;
        private String CallOptions_hns = 'CallOptions=http://soap.sforce.com/schemas/class/AddPdfToRecord';
        private String AllowFieldTruncationHeader_hns = 'AllowFieldTruncationHeader=http://soap.sforce.com/schemas/class/AddPdfToRecord';
        private String SessionHeader_hns = 'SessionHeader=http://soap.sforce.com/schemas/class/AddPdfToRecord';
        private String DebuggingHeader_hns = 'DebuggingHeader=http://soap.sforce.com/schemas/class/AddPdfToRecord';
        private String DebuggingInfo_hns = 'DebuggingInfo=http://soap.sforce.com/schemas/class/AddPdfToRecord';
        private String[] ns_map_type_info = new String[]{'http://soap.sforce.com/schemas/class/AddPdfToRecord', 'addPDFStub'};
        public void addPDF(String[] accountIds) {
            addPDFStub.addPDF_element request_x = new addPDFStub.addPDF_element();
            addPDFStub.addPDFResponse_element response_x;
            request_x.accountIds = accountIds;
            Map<String, addPDFStub.addPDFResponse_element> response_map_x = new Map<String, addPDFStub.addPDFResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://soap.sforce.com/schemas/class/AddPdfToRecord',
              'addPDF',
              'http://soap.sforce.com/schemas/class/AddPdfToRecord',
              'addPDFResponse',
              'addPDFStub.addPDFResponse_element'}
            );
            response_x = response_map_x.get('response_x');
        }
    }
}

Next create a class with the future method:

global class AccountTriggerController{

    @Future(callout=true)
    public static void addPDFAttach(string sessionId, list<id> accountId){
        addPDFStub.SessionHeader_element sessionIdElement= new addPDFStub.SessionHeader_element();
        sessionIdElement.sessionId = sessionId;

        addPDFStub.AddPdfToRecord stub= new addPDFStub.AddPdfToRecord();
        stub.SessionHeader= sessionIdElement;
        stub.addPDF(accountId);
    }
}

FInally create the trigger:

trigger accountAfterInsert on Account (after insert) {

     list<id> accId = new list<id>();
     for(id acc: trigger.newMap.keySet()){
         accId.add(acc);
      }
		//You would need to send the session id to the future method as the you cannot use the userInfo.getSessionID() method in the future method because it is asynchronous and doesn't run in the user context.
        AccountTriggerController.addPDFAttach(userInfo.getSessionId(), accId);

}

All of this would work only if you add the host in my case it’s https://ap1.salesforce.com, add it to the remote site setting. So go to Setup-> Admin Setup -> security Controls -> Remote Site Settings. Click on new, give it a name(webserviceTest), add the Remote Site URL(just copy paste the url from the address bar), it will only take the host and truncate the rest when you save it.

Hope it helps!!

UPDATE

I have updated the post with the test Classes. Now all the classes have more than 90% coverage!
ALso I have made some changes in the AddPdfToRecord class to accommodate the Test class changes
Below test classes needs to be added to get the coverage

First add the web service mock implementation and then the actual test class.

@isTest
global class WebServiceMockImpl implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
           String[] accountIdArray = new String[]{};
       addPDFStub.addPDFResponse_element respElement = new addPDFStub.addPDFResponse_element();
       addPDFStub.AllowFieldTruncationHeader_element class1= new addPDFStub.AllowFieldTruncationHeader_element();
       addPDFStub.DebuggingHeader_element class2= new addPDFStub.DebuggingHeader_element();
       addPDFStub.CallOptions_element class3= new addPDFStub.CallOptions_element();
       addPDFStub.DebuggingInfo_element  class4= new addPDFStub.DebuggingInfo_element ();
       addPDFStub.SessionHeader_element class5= new addPDFStub.SessionHeader_element();
       response.put('response_x', respElement ); 
   }
}
@isTest
public class AddPDFtoRecordTest{
    @isTest static void addPDFtoRecordTestMethod() { 
        Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
        account a = new account();
        a.name= 'test PDF';
        insert a;
        
        AddPdfToRecord.addPDF(new list<Id>{a.Id});    
    
    }
}

UPDATE
YOu can achieve the same by using the APEX Rest Resource. Check out the post here

You can find the code on gitHub

Using jQuery’s AutoComplete in Salesforce – Part 2

In the first part we saw that we are using a static array to show the country value. This is of no use in real-time scenario. In most of the cases one will be required to show the values from some where else. So how do we do it in salesforce??

In this example we will use the account and contact object to get the data.
Now, there are 2 ways to get the data from the database.
1.) Use a controller, which will return you a list of accounts.
2.) Query directly in the VF page using the Salesforce’s Ajax toolkit.

sfdcAutocomplete

I will demonstrate both the ways in the same code.

Step 1: Create an apex class with the below code. The name of the class is AutoCompleteDemoController
Step 2: Create a the VF page with the below code. Name the VF page : AutocompleteDemoPage

Apex Class:

public class AutoCompleteDemoController{
    public list<account> getAccountList(){
        return [select id,name from account limit 25];
    }
}

VF page:

<apex:page controller="AutoCompleteDemoController">
    <!--Make sure you have the Javascript in the same order that I have listed below.-->
    <script src="https://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="/soap/ajax/26.0/connection.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
    <script type="text/javascript">
        var j$ = jQuery.noConflict();
        var apexAccountList =[];
        
        //use the <!-- <apex:repeat> -->tag to iterate through the list returned from the class and store only the names in the javascript variable.
        <apex:repeat value="{!accountList}" var="accList">
            //Store the name of the account in the array variable.
            apexAccountList.push('{!accList.name}');
        </apex:repeat>
        
        //We will establish a connection salesforce database using the sforce.connection.init(sessionID, ServerURL) function.
        var sid = '{!$Api.Session_ID}';
        var server = "https://" + window.location.host + "/services/Soap/u/26.0";
        sforce.connection.init(sid, server);
        
        //We will query the contact object using the sforce.connection.query function. This will return 200 results.
        var result = sforce.connection.query("select Name from Contact");
        var records = result.getArray("records");
        var javascriptContactList =[];
        
        //Iterate thru the list of contact and store them in a javascript simple array variable which will then assign it to the source of the autocomplete.
        for(i=0;i<records.length;i++){
            javascriptContactList[i]=records[i].Name;
        }
        //on Document ready
        j$(document).ready(function(){
            
            j$("#apexaccountautocomplete").autocomplete({
                source : apexAccountList
            });
            j$("#sfjscontactautocomplete").autocomplete({
                source : javascriptContactList
            });
        });
    </script>
    
    <apex:form>
        <b>Account(This uses the Apex class to display the list)</b><input type="text" id="apexaccountautocomplete"/><br/><br/>
        <b>Contact(This uses the salesforce's ajax toolkit to display the list)</b><input type="text" id="sfjscontactautocomplete"/>
    </apex:form>
    
</apex:page>

P.S:This code may not work correctly in Google Chrome Browser initially.
Workaround: When you load the VF page for the 1st time in Chrome, you will see a shield (gray in color) in the address bar, click on it and select ‘Load unsafe javascript’. Another option is to load the script in the static resource and refer the scripts from there in the VF page.

Using jQuery’s AutoComplete in Salesforce – Part 1

Using the Auto-Complete plugin enhances the UI functionality. Whenever a user enter a value in a input field, the auto-complete will show the user a possible set of value which matches the user input value.

autoComplete
Now, Just to show an example , I will use the auto-complete functionality on a country input field. When a user starts entering a value, based on his entry we will show the possible values. We will make use of the jQuery auto-complete plugin. This plugin makes it very simple to implement the autocomplete in salesforce, any HTML content for that matter.

In the first example we will use the plugin in a VF page then we will implement a similar functionality on a standard page.

Step 1: Create a VF page, I will name it AutoCompleteExample
Step 2: Copy the below code and save the page.
Step 3: Open the VF page you have just created (https://yourSaleforceInstance/apex/AutoCompleteExample). You will be able to see a input field, Start entering some text. Voila!! you will be able to see autocomplete in Action.

<apex:page>
	<!--Make sure you have the Javascript in the same order that I have listed below.-->
	<script src="https://code.jquery.com/jquery-1.8.2.js"></script>
	<script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
	<link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
	<script type="text/javascript">
		//Create a new variable j$ just to avoid any conflicts with other libraries which may be using $.
		var j$ = jQuery.noConflict();
		//Capture the list of countries in a Array.
		var countryArray = ['India', 'USA', 'China','FInland','Norway','Netherlands','England','Ukraine','Russia','Japan','Korea','Burma','Srilanka','Iran','Iceland','Canada','Rome','Australia','Armenia','Albania','Afghanisthan'];
		//on Document ready
		j$(document).ready(function(){
			j$("#countryautocomplete").autocomplete({
				source : countryArray
			});
		});
	</script>
	<apex:form>
		<b>Enter Text</b><input type="text" id="countryautocomplete"/>
	</apex:form>
</apex:page>

P.S: This code may not work correctly in Google Chrome Browser initially.
Workaround: When you load the VF page for the 1st time in Chrome, you will see a shield (gray in color) in the address bar, click on it and select ‘Load unsafe javascript’.