Tuesday, June 30, 2015

Parsing JSON in Apex

This article will explain how to parse JSON content and deserialize  JSON into Apex objects.

Use the JSONParser methods to parse a response that's returned from a call to an external service that is in JSON format, such as a JSON-encoded response of a Web service call out.

There are 2 ways you can parse JSON in apex. We will cover both option and their benefits.

1. Parsing JSON by inspecting each JSONToken present in JSON

Generally this method is useful for grabbing specific pieces of data from JSON. The System.JSONToken is an enumerator that provides values such as FIELD_NAME, START_OBJECT, END_OBJECT and others that inform you of the type of token currently being parsed.
Below is sample JSON (JSON response from callout to Box.com) which we will be using here for parsing.


Now suppose if we have to fetch the session id from JSON, then we will be using below code:

HTTPResponse res=sendHttpRequest(req);
String response=res.getBody();
String SessionId='';
JSONParser  parser = JSON.createParser(Response);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){
String fieldName = parser.getText();
String fieldValue=parser.getText();
if(fieldName == 'type' && fieldValue=='session') {
SessionId= parser.getText();

The code above executes a while loop that walks through the entire JSON string using the parser.nextToken() method and parses simple field text values such as id or session using the parser.getText() method.

If we need only specific information like session id, then we will check token value as id after type and session token. After getting the session id, we are breaking the loop so that we are not getting any other token with value id in JSON.

Points to remember while using this approch:
  • If you want specific information from JSON, then use this approach instead of storing all JSON information in apex objects.
  • Developer has to check different tokens in order to get required value from JSON.

2. Parsing JSON by deserializing It into Object

In this approch, we are going create a apex class and deserialize the JSON to store information in apex class variable. This approach is very simple but the only thing is that you need to defined Apex classes mapped to each of the element/entity represented in the JSON string.

You can refer below URL in order to generate apex class structure for JSON.


Paste your JSON in this tool and it will generate required apex class for deserializing the JSON. Below is class generate for above sample JSON response:

You can define getter setter methods for variables if you want to display on VF page like:
public String type {get;set;}
public String type {get;set;}

If we are using inner class to store values, then we can remove the parse method and testmethod from above generated apex code. Below is simplified version of class which we can be used to deserialize JSON:

public class JSON2Apex {
public class Document {
public String type;
public String id;
public String status;
public String name;
public String created_at;
public class Urls {
public String view;
public String assets;
public String realtime;
public String type;
public String id;
public Document document;
public String expires_at;
public Urls urls;

Now we have apex class required to deserialize the JSON String. We can deserialize the JSON with single line of code in apex mentioned below:

HTTPResponse res=sendHttpRequest(req);

String response=res.getBody();
JSON2Apex   JSONDetails=(JSON2Apex) System.JSON.deserialize(response, JSON2Apex.class);

Now you will have all information from JSON into apex class variables.

Points to remember while using this approach:
  • It is not required that you have to create variables for all elements/entity in apex class. In our example, if you don't want fetch urls information from JSON, then you can remove URLs public class. from JSON2Apex class. Also you can remove other variables like type, created_at etc from JSON2Apex class if not required in your apex class.
  • For multi-level nested JSON, you are limited by the depth of inner class as you can only have one level of inner class in apex. If you need to parse deeper nested JSON, then use parsing through tokens.

Sunday, June 21, 2015

Box and Salesforce Integration

In this blog, I am going to explain how to integrate Box.com and Salesforce using Apex and VF in order to upload document to Box and to view files present in Box in VF page.

First of all, Create a Box Application

Create Box content application which will help us to upload files directly from Salesforce to Box.com.  After creating app, copy client_id and client_secret values and specify your VF page URL as redirect_uri in Oauth 2 parameters section.

Now create another application and select Box view application. This will help us to view files in VF page. View API allow to convert files in HTML format for easy display in web pages. Copy view API Key from General information section.

Now Create a custom setting in Salesforce to store client_id,client_secret, access token, refresh token and View API key.

Now Create Remote site setting in order to do call out to Box.com.

Now create a VF page "boxAuthPage" and apex class "boxAuthPageController". Code is provided in end of this blog. Please scroll down to copy code and paste in your VF and apex class.

Snapshot of VF page:

Store client_id, client_secret, view api key in custom setting record. While creating custom setting record, I have specified "Box_sunil02kumar' as name for custom setting. If you want to use other name, then replace "Box_sunil02kumar' in apex class with your custom setting name.

Open VF page and click on Authorize Box button, system will redirect you to login page where you need to enter you box login credential and then a click grant access to box button.

All folder present in box will be listed in Folders drop down. When you select any particular folder, all files present in that folder will appear in page block table. When you click on "View" link, file will open on right side of page.

If you have box account, then use below url to test the functionality. Create folders in your box account and upload pdf and doc files in it. If you upload files with already existing file name in Box folder, then you will get error.


I have built this page for demo. So every time you refresh this page, you need to again authorize it by clicking on Authorize box button. Actually I am not storing access token or refresh token or any user credentials and also scope of these variables are same as that of VF page. Also client id, client secret and access tokens are not displayed in demo page but if you follow all steps mentioned above including custom setting and remote site setting, then you will get complete UI.

Important information which will help you to understand apex class:
  • Uploading data into box.com uses content type as multipart/form-data.
  • You can not send a file to server which is expecting a binary. So you need to encode the base64 in binary supported format.
  • In order to view document, first you need to send request to get temporary download URL by sending file id to Box.com. Temporary download URL is returned in response Location header. This URL can be used to download file.
  • Once you get temporary download URL, sent request to BOX.com to get temporary document id. In HTTPRequest, you need to pass temporary download URL in body.
  • Now this document id which you get in response can be used to generate session id for file which will be used to view file in iframe in VF page. When you do call out to get session id, pass temporary document id in request body.
  • If file is processed by Box.com and is ready to view, then in response you will get session id. If your request is accepted but file is not yet converted to HTML format then in response header, you will time duration after which file will be ready. This information is present in 'retry' header in response.
  • Once you get file session id from Box.com, then you use it view file in iframe in your VF page by using  URL: https://view-api.box.com/1/sessions/'+fileSessionId+'/view

  • You can upload any type of file to box folder.
  • Before uploading any file, please select folder in which you want to upload file.
  • As per my knowledge, View API doesn't support jpg and png images. 
  • You can easily view any pdf or word file from Box in SFDC using view api.
  • You can also specify download URL. Please refer Box content view API for this.
  • In apex, code is specified to get file download URL in FindFileDownloadUrl method in apex class.
This blog will help you to basic understanding of how to achieve integration between Box and SFDC by using apex code. After going through this code, you can easily modify the code as per your requirements.

Code for VF and apex class:

Tuesday, April 28, 2015


REST API provides a powerful, convenient, and simple Web services API for interacting with Force.com. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web 2.0 projects.

A REST resource is an abstraction of a piece of information, such as a single data record, a collection of records, or even dynamic real-time information. Each resource in the Force.com REST API is identified by a named URI, and is accessed using standard HTTP methods (HEAD, GET, POST, PATCH, DELETE). The Force.com REST API is based on the usage of resources, their URIs, and the links between them. You use a resource to interact with your Salesforce or Force.com organization. For example, you can:
  •  Retrieve summary information about the API versions available to you.
  • Obtain detailed information about a Salesforce object such as an Account or a custom object.
  • Obtain detailed information about Force.com objects, such as User or a custom object.
  • Perform a query or search.
  • Update or delete records.

In this blog, I will be explaining how to interact with Salesforce using REST API.  I will be creating a VF page named as “RESTAPIPlayground”. On this page you can specify different parameters which is required to send HTTPRequest like Access token, end point URL (URI), HTTP method etc. VF page will display the response from Salesforce and will also display the Apex code to send HTTPRequest.

Here I assume that you are aware of how to generate access token from salesforce using oAuth2.0. If you want to learn this first then refer to my earlier blog:

Once you have access token of salesforce with which you want to interact then you can use this playground (VF Page) to play with different options available under REST API.

Create a Apex class "RESTAPIPlaygroundController" and VF Page "RESTAPIPlayground". Below is code for Apex Class and VF page.

Below is snapshot of REST API Playground. You can specify the Access_Token, REST API service URI (endpoint URL), HTTP method and content type (json or xml), request body (in case of patch and post method). Once you click on send request, system will display the HTTP response.

Note: Add the REST API service URI (end point URL) to remote site settings before sending HTTPRequest.

Friday, April 24, 2015


OAuth (Open Authorization) is an open protocol to allow secure API authorization in a simple and standardized way from desktop and web applications. The Force.com platform implements the OAuth 2.0 Authorization Framework, so users can authorize applications to access Force.com resources (via the Force.com REST and SOAP Web Service APIs) or Chatter resources (via the Chatter REST API) on their behalf without revealing their passwords or other credentials to those applications. Alternatively, applications can directly authenticate to access the same resources without the presence of an end user.

In this blog, I will be specifying different steps which we need to perform in order to generate Access token for Salesforce org. We will be using 2 different developer org. In org 1, we will be writing all code to generate access token for another org.

In order to access token from different org and storing different required information, we will create custom object (External_Application__c) and create different fields mentioned below:

Field Label
Field Name
Data Type
Access Token
Text Area(255)
Application Name
Text(255) (Unique Case Insensitive)
Authorization Server Response
Long Text Area(32768)
Callback URL
Text Area(255)
Client ID
Text Area(255)
Consumer secret
Text Area(255)
Text Area(255)
Instance URL
Text Area(255)
Issued at
Text Area(255)
Outh Code
Text Area(255)
Text Area(255)
Salesforce Domain
Text Area(255)

Different steps involved in order to get access token:

Login to developer organization (org 2) for which you want to generate access token.
  1. Navigate to Setup Create Apps, and in the Connected Apps section, click New to create a new connected app and click Enable OAuth Settings to open the API section.
  2. Specify name (here I am specifying "Rest Playground"), check enable OAuth settings checkbox and specify callback URL (in my case- https://xxx.salesforce.com/apex/WebServerAuthentication?AppName=SunilKumar04). here xxx refer to domain name for example ap1,ap2 etc.
  3. You may leave “Selected OAuth Scopes” blank.
  4. Click on Save. You will get consumer key and consumer secret key. Copy these 2 keys values and store it in notepad.

Now login to developer organization (org 1) where you will be writing whole logic to find access
token for org 2.
  • Create a custom button "Refresh Access Token" in External Application object. 

  • Create a VF page “WebServerAuthentication” and apex class “WebServerAuthenticationController”.

  • Add custom button "Refresh Access Token"  to External Application page layout.
  • Create Remote Site Settings records. Specify domain name of org 2 for which you want to fetch access token.

  • Now create a External Application records. Specify consumer key (generated while creatin connected app in org 2) in client id field. Enter consumer secret and callback URL as present in connect app record in org 2.

Now we ready to generate access token which for org 2. Go to detail page of  record which you created. I have created record with name as "SunilKumar04".  Click on Refresh Access Token.
System will redirect you to salesforce login page. Enter the credential of org 2 for which you want access token. After logging, if system ask any permission then click on Allow button. After that you will be redirected to org 1 and you can see the response details on External Application record detail page.


  • If you are integrating 2 developer org, then create domain in your developer org and use domain URL  as endpoint URL in Httprequest.
  • You can connect to different org. Create different records in External Application object for different org.
  • For more detailed information on obtaing access token, please refere below URL  https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com

Tuesday, March 31, 2015

Tooling API Overview

Tooling API provides SOAP and REST interfaces that allow you to build custom development tools for Force.com applications. For example, you can:
  • Add features and functionality to your existing Force.com tools.
  • Build dynamic modules for Force.com development into your enterprise integration tools.
  • Build specialized development tools for a specific application or service.

Tooling API exposes objects used in developer tooling that you can access through REST or SOAP, and works just like the Salesforce REST API and SOAP API.

Tooling API provides both SOAP and REST interfaces.
  • Use REST API if you’re using a language that isn’t strongly typed, like JavaScript.
  • Use SOAP API if you’re using a strongly typed language like Java that generates Web service client code. 

Tooling REST API

The base URI for each Tooling REST API resource is http://domain/services/data/vXX.X/tooling/ where domain is a Salesforce instance or a custom domain and vXX.X is the API version number. For example: http://na1.salesforce.com/services/data/v28.0/tooling/

For complete list of Tooling API resources, refer below URL:

Available Custom Objects using tooling API

If you have to find out all available custom objects in your org, then use below code sample :

Available Validation Rules using Tooling API

Below apex code will give all validation rules in your organization:

Tooling API can be used to perform the following tasks

  • Manage working copies of Apex classes and triggers and Visualforce pages and components using the ApexClassMember, ApexTriggerMember, ApexPageMember, ApexComponentMember and MetadataContainer objects.
  • Manage working copies of static resource files using the StaticResource object.
  • Check for updates and errors in working copies of Apex classes and triggers and Visualforce pages and components, and commit changes to your organization using the containerAsyncRequest object.
  • Execute anonymous Apex. 
  • Manage custom fields on custom objects using the CustomField object.
  • Access code coverage results using the ApexCodeCoverage, ApexOrgWideCoverage and ApexCodeCoverageAggregate objects.
  • Execute tests, and manage test results using the ApexTestQueueItem and ApexTestResult objects.
  • Manage validation rules and workflow rules using the ValidationRule and WorkflowRule objects.

Monday, March 16, 2015

Spring 15 Release-Enhancements and new Features

The Force.com Spring '15 Release introduces compelling new enhancements and features that will automate time-based processes, enhance mobile experiences and streamline your overall development. Run more tests in Sandbox and Developer orgs, and monitor jobs for asynchronous execution.

Analytics: Introducing Wave, the Analytics Cloud

Analytics Cloud gives you a fast, fluid way to drill through data, discover compelling insights, and share the right visuals to tell your data story. Datasets, lenses, dashboards, and apps are collections of data that represent different levels of refinement—everything from raw data uploaded from your source systems to highly curated, packaged views of your data. With the mobile-first Analytics Cloud, you can explore all types of data from your mobile device. Check in on this quarter’s customer cases, track progress toward sales goals, and instantly share learnings.

With new Salesforce analytics clouds, users can gain insight in your business through data. Users can:
  • User can explore millions of data points from multiple sources with ease.
  • Insights are not and should not be restricted to the desktop. With the mobile-first Analytics Cloud, you can explore all types of data from your mobile device. Check in on this quarter’s customer cases, track progress toward sales goals, and instantly share learnings with your team. No matter where you are, collaborate and share insights with colleagues and know your customers like never before.
  • User can share their findings with other teams or users.
Analytics Cloud brings data from different business process and systems. Data can be from Salesforce, data warehouses, CRM and ERP systems, log files, CSV files, XML files and more. Data Sources can be provided in structured, semi-structured or unstructured form. Salesforce uses powerful indexing technology. It provides capacity to scale to many rows with any data type.

Apex Code Enhancements

  • Submit More Batch Jobs with Apex Flex Queue: Submit up to 100 batch jobs simultaneously and actively manage the order of the queued jobs to control which batch jobs are processed first. This enhancement provides you more flexibility in managing your batch jobs.
  • Make Long-Running Callouts from a Visualforce Page: Use asynchronous callouts to make long-running requests from a Visualforce page to an external Web service and process responses in callback methods. Asynchronous callouts that are made from a Visualforce page don’t count toward the Apex limit of 10 synchronous requests that last longer than five seconds. As a result, you can make more long-running callouts and you can integrate your Visualforce pages with complex back-end assets.
  • Set Up Test Data for an Entire Test Class: Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in every test method in the test class. Test setup methods can be time-saving when you need to create reference or prerequisite data for all test methods, or a common set of records that all test methods operate on.
  • Chain More Jobs with Queueable Apex: Queueable Apex was introduced in Winter ’15 and enables you to easily start and manage asynchronous processes. Previously, you could chain a queueable job to another job only once. You can now chain a job to another job an unlimited number of times. For Developer Edition and Trial organizations, your chain can have up to five queueable jobs.
  • Access Address and Geolocation Compound Fields Using Apex: You can now access address and geolocation compound fields in Apex using the new Address and Location classes. Previously access only compound fields’ component fields in Apex. You can now query compound fields and their components using the new Address and Location class methods.
  • Make Apex Callouts with More Data: The callout size limit for requests and responses has been increased to the heap size limit. With a larger callout size for requests and responses, you can send and receive more data from an external Web service.
  • List Apex Classes and Triggers With a Tooling API Endpoint: Use the apexManifest Tooling API endpoint to list all of your Apex classes and triggers, including global classes and   triggers from your installed managed packages. Rather than querying both the ApexClass and ApexTrigger objects, you can retrieve a quick list of both classes and triggers with just one API call. Unlike ApexClass, apexManifest retrieves your inner classes—previously, you needed to get and parse the symbol table to retrieve your inner classes.
  • String Methods Fixed for Escaping Additional Characters: When you activate this update, these Apex String methods will escape additional characters: escapeHtml3, escapeHtml4, and escapeEcmaScript.

Salesforce 1 Enhancements 

  • You can turn your users into power users with Salesforce Adoption Manager. If you enable this feature, users receive customized suggestions based on how they work in both the full Salesforce site and the Salesforce1 mobile app. To enable Salesforce Adoption Manager, from Setup in the full Salesforce site, click Manage Users > Adoption Manager and select Enable Salesforce Adoption Manager.
  • Salesforce introduce Create New task that allows end users to create task directly from post in their chatter feed.
  • To take advantage of the larger screen on tablets, Salesforce1 uses a different object home page interface than what’s provided on smartphones. Tablet users can see more details about recently viewed records, directly access standard and custom list views, and search across other objects as well as the current object. The tablet version of object home pages is currently available in the Salesforce1 mobile browser app app only.
  • When using Salesforce1 on tablets, users get an enhanced list view experience that shows more record details at a glance and includes more sorting options and intuitive controls for navigating through this extra information. The tablet version of list views is currently available in the Salesforce1 mobile browser app only.
  • When using Salesforce1 on smartphones, users can now see more than four list views for an object directly from an object’s home page. It’s no longer necessary to first open a specific list view to access other list views. When using the mobile browser app, simply tap More List Views on an object home page. (If a user hasn’t yet accessed any list views at all, the option is Show List Views.) Users see up to 200 list views for the object, including list views that haven’t been accessed recently in the full Salesforce site.
  • Now users can add a file and a link directly from the New Post page. This feature is available in the Salesforce1 mobile browser app only.
  • If Chatter Questions is enabled for your organization, you can give moderators the ability to escalate questions in Chatter to cases, making it easier to track and resolve your customers’ issues. Question-to-Case is available in the Salesforce1 mobile browser app only.
  • Put all your content at users’ fingertips. If Files Connect is set up for your organization, Salesforce1 mobile browser app users can browse and share files from external data sources, such as Microsoft SharePoint and OneDrive for Business.
  • Data.com Duplicate Management lets you control whether and when you allow users to create duplicate records inside Salesforce. Set up duplicate rules in the full Salesforce site and you can also manage whether Salesforce1 users can save records that are identified as possible duplicates. Duplicate management is now generally available in all versions of the Salesforce1 mobile app. Duplicate rules tell Salesforce what action to take when users attempt to create records that might duplicate existing Salesforce records. For example, the rule could block users from saving the possible duplicate record or allow them to save it anyway.
  • Records with standard address fields now display a Google Maps image of the address. This saves user’s time by letting them see where their contacts or accounts are located, instead of having to locate addresses in an external map application. This feature is available in all versions of Salesforce1.
  • Sales representatives on the go can now convert qualified leads to contacts and create opportunities (beta), which helps sales representatives grow their revenue pipeline. This option is available in all versions of Salesforce1.

Salesforce1 Reporting Enhancements

  • Subscribe to Receive Report Notifications: Your users can now sign up for report notifications, to stay up-to-date on the metrics they care about most. Subscribe to a report and set the conditions that should trigger notification.
  • Increase the Session Security Level Required to Export and Print Reports: You can now set a security policy that requires users to have a high assurance session to export and print reports. Set this policy to restrict access to users who can perform these tasks. Previously, you could require a high assurance session to access resources like reports, dashboards, and connected apps. Now, to give you finer access control, you can also require a high assurance session to restrict access to exporting and printing reports.
  • Dashboard Wizard and API Create Correct Relative URLs:  The dashboard wizard and API no longer cause errors when you enter Drill Down to locations other than absolute URLs. To fix a potential security issue, the dashboard builder, wizard, and API now create correct relative URLs when you use text to represent the location Salesforce takes users to when they click a dashboard component. The text you enter is escaped with a backslash and converted into a relative URL. All three ways of creating dashboard components accept absolute URLs as is and don’t convert them to relative URLs. (Absolute URLs look like salesforce.com and www.salesforce.com)
  • The Reports and Dashboard Tabs Are Protected from Clickjacking: For enhanced security, clickjack protection is now enabled for Salesforce1 Reporting. This means that the Reports and Dashboards tabs can no longer be embedded inside an iframe. Previously, you could turn clickjack protection on and off. Now, clickjack protection is always active.

Lightning Process Builder

The Process Builder is a new workflow tool that helps you easily automate your business processes by providing a powerful and user-friendly visual representation of your process as you build it. The Process Builder’s simple and powerful design allows you to:
  • Create your processes using a convenient visual layout with point-and-click efficiency.
  • Create your whole process in one place rather than using multiple workflow rules.
  • Create processes by collaborating with different teams in your business.
  • Stop using Apex code to automate simple tasks.
Automated processes in the Process Builder consist of criteria that determine when to execute action groups and immediate and scheduled actions to execute when those criteria are met. Any change that causes a record to match the criteria can automatically trigger the action group.
You can use the more powerful and flexible Process Builder to perform the same actions as workflow. The process builder doesn’t support outbound messages, but you can easily create one yourself with Apex. With the Process Builder, you can:
  • Create a record
  • Update any related record—not just the record or its parent
  • Use a quick action to create a record, update a record, or log a call
  • Launch a flow—as an immediate or a scheduled action
  • Send an email
  • Post to Chatter
  • Submit for approval
If you need your process to do more than what those actions allow, don’t worry. You can also call Apex from a process.

Manager Groups

Share records up or down the management chain using sharing rules or manual sharing or apex managed sharing. Manager groups were previously not automatically enabled in your organization. With Spring ‘15, you can enable this feature on the Sharing Settings page.
  • Allows users share records with their management chain, instead of all managers in the same role.
  • Manager groups can be used wherever other groups are used, such as in a manual share or sharing rule. But they cannot be added to other groups and don’t include portal users.
  •  Manager groups can contain Standard and Chatter Only users only.

Import Accounts and Contacts with Ease

My Accounts & Contacts wizard, which makes it even easier to get accounts and contacts from the data sources that matter to you into Salesforce. If you have a new Salesforce organization, you can get to the wizard from the Accounts and Contacts tabs in Salesforce. Or, just click Your Name > My Settings > Import > Import My Accounts & Contacts, and then start the import wizard.
You can import Accounts & Contacts from 15 different sources like Outlook, Excel, Gmail, LinkedIn, Act, Quickbook etc.

Tuesday, February 17, 2015

Visualforce Remote Objects

JavaScript remoting is a popular, powerful, and efficient method for building web apps with Visualforce, especially for creating pages for use in Salesforce1, or working with JavaScript libraries like jQuery or AngularJS. Visualforce Remote Objects are proxy objects that allow basic DML operations on sObjects directly from JavaScript. Remote Objects take some of the complexity out of JavaScript remoting, by reducing the need for @RemoteAction methods in an Apex controller or extension. Like JavaScript remoting, Remote Objects calls don’ t count towards API request limits.

Using Visualforce Remote Objects consists of implementing two separate pieces of functionality on the same page.
• Access definitions, written in Visualforce using the new Remote Objects components. These components generate a set of JavaScript proxy objects that you can use in the next step.
• Data access functions, written in JavaScript. These functions use the proxy objects made available by the access definitions to perform create, select, update, and delete operations on your data.

Your page then uses the data access functions to respond to user interaction, including form submissions or controls changes, or in response to timers, or pretty much anything you can write in JavaScript.

Below are some sample example where Visualforce remote objects being used:
  • Create new record with Visualforce Remote Objects
Create a record by calling create() on a Remote Objects model instance.
create() accepts two arguments, both optional
RemoteObjectModel.create({field_values}, callback_function)

The field_values block enables you to define and create a record in one statement. Set field values as you do when you create a model, using a JSON string. For example, the following two calls to create() are equivalent. The callback function enables you to handle the server response asynchronously.

Below is code snippet:

  • Retrieve records from object with Visualforce Remote Objects
Retrieve records by calling retrieve() on a Remote Objects model instance.Retrieve() requires two arguments, one for query criteria and one for a callback handler.
RemoteObjectModel.retrieve({criteria}, callback_function)

criteria can be a Remote Objects query object or a function that returns one.

Below is code snippet:

Points to remember:

  • Remote Objects respects your organization’s field level security settings. Keep this in mind when you create pages that use Remote Objects. Fields that aren’t accessible to the person viewing the page appear blank. Actions that modify field data (create(), update(), and upsert()) fail with an error if they include inaccessible fields in the request.
  • Each Remote Objects operation (create(), update(), and so on) is a separate transaction. Each operation succeeds or fails on its own, which can be a problem when you need to create or modify multiple related objects as part of a business process. In contrast, JavaScript remoting transaction boundaries are on the Apex@RemoteAction method. It’s easy to create the invoice and related line-item records inside one method, where automatic Apex transactions ensure that all records are created together or not at all.
  • Remote Objects calls aren’t subject to API limits.
  • You can retrieve a maximum of 100 rows in a single request. To display more rows, submit additional requests by using the OFFSET query parameter.
  • Setting the rendered attribute to false on Remote Objects components disables the generation of the JavaScript for those Remote Objects. Any page functionality that depends on unrendered Remote Objects should also be disabled.
  • Remote Objects isn’t a way to avoid Salesforce service limits. Remote Objects calls aren’t subject to API limits, but Visualforce pages that use Remote Objects are subject to all standard Visualforce limits.

Sunday, January 25, 2015

Onclick Javascript-AJAX Toolkit

When working with small amounts of data, use the AJAX Toolkit.
AJAX works best with relatively small amounts of data (up to 200 records, approximately six fields with 50 characters of data each). The larger the data set returned, the more time it will take to construct and deconstruct a SOAP message, and as the size of an individual record gets larger, the impact on performance becomes greater. Also, as more HTML nodes are created from the data, the potential for poor performance increases. Because browsers are not efficient, careful consideration needs to be given to browser memory management if you intend to display a large amount of data.

The following are examples of appropriate uses:
  • Updating a single record.
  • Modifying few fields of related child records.
  • Perform one or more simple calculations and then update a record.
Here I will be sharing basic sample code for 3 scenarios mentioned above.
  1. Updating a record
Support users can assign cases (assign to queue) to themselves by clicking on "Accept" button present in Case detail page. On click on "Accept" button, system will change the case ownerid to current logged in user. Below is sample code:

  1. Updating child records or list of records

Notify Contacts of Account to update their Contact details. Create a checkbox field(contact_update_required__c) in Contact. Create a workflow rule which will send email to all contacts to update their contact details whenever checkbox field is true. Create a related list button for Contact object “Update Contact Details” and add it to Contact related list on Account page layout. Whenever this button is clicked, onclick javascript modify the checkbox field to true in all related contacts of Account.

  1. Performing logic by calling apex method
There are few scenarios where you want to perform complex logic in apex class and want to execute that logic on click of button. For example, you want send notifications to attendees of event based on some logic. For this, you need to create global class and create webservice method and then call it from onclick javascript.

Others capabilities of AJAX  toolkit are:

  • Performing synchronous and asynchronous calls.
  • Query,create,edit,delete,undelete,merge and search records. 
  • Convert lead,send email and initiate approval process.
  • Use describe to get object and fields information.
Refer below URL for more reference on AJAX toolkit:

Friday, January 2, 2015

Creating custom lookup field in VF page for objects

Recently I got requirement in which I have to store information like Email template name, frequency of sending emails and few other fields in custom object. While selecting email template, salesforce standard look up pop should open which usually comes while creating Email Alerts (for selecting email template). Already custom fields like EmailTemplateid (text), and EmailTemplateName(text) were created in custom object. Also user want flexibility to create many records at once.

Below is sample code to create custom look up in VF page for email template:


First look at input elements:
  • Input text with id='Template_lkid' stores email template id.
  • Input text with id="Template_lkold" stores email template name.

Now look at javascript function:

JavaScript:openLookup('/_ui/common/data/LookupPage?lkfm=editPage&lknm='+templatenameid+'&lkrf=&epf=1&lktp=00X',670,'1','&lksrch=' + escapeUTF(getElementByIdCS(templatenameid).value.substring(0, 80)))";

About parameters which need to be set for replicating standard look up behaviour:

  • lknm : This specify the id of input text where selected value in pop up will display
  • lktp : This is object prefix( first 3 characters). in my case '00X' prefix for Email Template
  • lksrch : This is search parameter. If you specify text, then in pop up system will search and show results.
  • In order to store id of record selected in pop up, this function search input text field with id equal to value passed for lknm parameter appended by '_lkid'. For example, if we pass 'Template' as value for lknm parameters, then selected record id will be populated in input text field with id='Template_lkid'.

I have used <apex:inputtext/> tag inside pageblocktable, salesforce generate unique ids while rendering page. As it is repeating element, salesforce append numbers(index) starting from 0 (for first element) in front of id specified in apex:input tag. So in order to populate selected values to correct input text elements, I have created a counter variable in my wrapper. So whenever user clicks on lookup icon, I am passing the element id in javascript and extracting index (counter value) from it and then creating requird id which will be passed for lknm parameter.

In order to implement custom look up for other object, just change object prefix in javascriot openLookup function and it will work. For example, Account object prefix is '001'. Just change '00X' to '001' in order to open pop up for account records.


Hope this will help someone.
looking forward your comments and suggestions...