When you dabble in code, every day is an adventure and opens a window of new opportunities to experiment and challenges. The mantra of the codingFINAL TRAIN IMAGE game is to keep oneself ahead of the game and have that extra edge. Therefore, today we would like to introduce to you the concept of Visualforce Javascript Remoting which is a technique within Salesforce to call methods in a class via Javascript.

If this has got you wondering how it will help, here are top 3 reasons that answer your why:

Need for Speed – Of course, remoting will help you set up the fastest way of calling controller code and passing data back and forth from the page.

Freedom from Forms – The good news is that you don’t have to use forms whether it is Apex or anything else. What is helpful is that you do not have to pass or store all the data for the controller calls!

Being ahead of the game – The third reason is perhaps the best because remoting helps you be asynchronous. Through this you can start loading data for pages the user has not even accessed yet!

Now, let us see what is JavaScript remoting all about:

1. The remote method invocation you add to the Visualforce page is written in JavaScript.
2. The remote method definition is written in Apex, but there are few differences from normal action methods.
3. The response handler callback function you add to or include in your Visualforce page is written in JavaScript.

Here’s how it is done:

Page JavaScript:

<script type=”text/javascript”>
function getRemoteAccount() {
var accountName = document.getElementById(‘acctSearch’).value;
Visualforce.remoting.Manager.invokeAction(
‘{!$RemoteAction.MyController.getAccount}’,
accountName,
function(result, event){
if (event.status) {
// Code for callback handling
}
}, {escape: true}
);
}
</script>

Controller:

@RemoteAction
global static String getItemId(String objectName) { … }

 

VF Remote Objects

What are VF remote objects? Visualforce Remote Objects are proxy objects that allow basic DML operations on sObjects directly from JavaScript.

How do the JavaScript remote objects help? Remote Object controller work wonders by sharing rules, field level security and data accessibility concerns.

Using Visualforce Remote Objects consists of two parts:
1. Defining Remote objects.
2. Data access functions are written in JavaScript which use the proxy objects made available by the access definitions to perform create, select, update, and delete operations on your data.

Here’s how we define remote objects which specify objects and fields to make accessible on the page:
Syntax:

<apex:remoteObjects >
<apex:remoteObjectModel name=”Warehouse__c” jsShorthand=”Warehouse” fields=”Name,Id”>
<apex:remoteObjectField name=”Phone__c” jsShorthand=”Phone”/>
</apex:remoteObjectModel>
</apex:remoteObjects>
<apex:remoteObjects>

Use this component, along with child and components, to specify the sObjects and fields to access using Visualforce Remote Objects.

<apex:remoteObjects>

Defines an sObject and its fields to to create accessibility using Visualforce Remote Objects. This definition can include a shorthand name for the object, which you can use in JavaScript instead of the full API name. This is especially useful if your organization has a namespace or if you’re packaging an app, and it helps make your code more maintainable.

<apex:remoteObjectField>

Defines the fields to load for an sObject. Fields defined using this component, instead of the fields attribute of , can have a shorthand name, which allows the use of a “nickname” for the field in client-side JavaScript code, instead of the full API name. Use as child of .

Methods:

Retrieving records:
var wh = new SObjectModel.Warehouse();
wh.retrieve({ limit: 10 }, function(err, records){
if(err) alert(err.message);
else {
// Code to display records
}

Retrieve records with where condition:
var src = new SObjectModel.getActs();
src.retrieve({ limit : 10,
where : { cType :{eq : ‘Banking’}}
} ,
function(err,records){
if(err == null)
{
//Process returned “records” to display in Visualforce code.
}
} );

Save record:
var record = new SObjectModel.Account({
Id: id,
BillingState: stateVal ,
Phone: PhoneVal ,
});
record.update(Dataload);

Delete Record:
var AccountTodelete= new SObjectModel.Account();
AccountTodelete.del(id,Dataload);

Create Record:
var recordToinsert = new SObjectModel.Account({
Name: Nameval,
BillingState: stateVal ,
Phone: PhoneVal ,
});
recordToinsert.create(Dataload);

 

Important Notes:
1. Remote Objects respects your organization’s field level security settings. The 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.
2. Remote Objects use an object to specify criteria for retrieve() operations. Use this object to specify where, limit, and offset conditions for your queries.
The structured format of the query object enables Visualforce to validate the criteria at save time which reduces the likelihood of runtime errors.

var ct = new RemoteObjectModel.Contact();
ct.retrieve(
{ where: { FirstName: {eq: ‘Marc’},LastName: {eq: ‘Benioff’} },
orderby: [ {LastName: ‘ASC’}, {FirstName: ‘ASC’} ] limit: 1 },
function(err, records) {
if (err) {
alert(err);
} else {
}
}
);

The query criteria finds a contact named Marc Benioff and limits the query to a single result.
where Conditions:
where conditions enable you to filter the results of a retrieve operation, much the same way that a WHERE condition in a SOQL query does. The operators that are available for where conditions are:
eq: equals
ne: not equals
lt: less than
lte: less than or equals
gt: greater than
gte: greater than or equals
like: string matching. As with SOQL, use “%” as a wildcard character.
in: in, used for finding a value that matches any of a set of fixed values. Provide values as an array, for example, [‘Benioff’, ‘Jobs’, ‘Gates’].
nin: not in, used for finding a value that matches none of a set of fixed values. Provide values as an array, for example, [‘Benioff’, ‘Jobs’, ‘Gates’].
and: logical AND, used for combining conditions
or: logical OR, used for combining conditions
Within the where object, add field name and condition pairs to create complex criteria. Multiple conditions by default are treated as AND conditions. For example:
{
where:
{
or:
{
FirstName: { like: “M%” },
Phone: { like: ‘(415)%’ }
}
}
}
orderby Conditions

orderby enables you to set a sort order for your results and facilitates sorting up to three fields. Specify your orderby conditions as an array of JavaScript objects that contain name-value pairs. The field to sort on is the name, and the sort description is the value. The sort description enables you to sort ascending or descending and to sort null values first or last. For example:
orderby: [ {Phone: “DESC NULLS LAST”} , {FirstName: “ASC”} ]

limit and offset Conditions
limit and offset enable you to retrieve a specific number of records at a time and to page through an extended set of results.Use limit to specify how many records to return in one batch of results. The default value is 20. The maximum is 100.Use offset to specify how many records to skip in the overall result set before adding records to the returned results. The minimum is 1. There is no maximum limit.

This was the third edition from our series on “Apex programming tips and tricks” – Keep experimenting and reinventing!

AppShark is a Salesforce partner in Dallas