In Part 1 of this post, we looked at Remote Objects from a high level, examining what Remote Objects are and the reasons for using it. In this post, we’ll look at how to actually use Remote Objects on a page as well as some samples of the basic CRUD operations that can be performed.
Enabled Remote Objects on the page
Remote Objects is very easy to start using. If your organization has been upgraded to Winter ’15 (API 32), you already have Remote Objects. To start using them on your custom Visualforce pages, you will need to use a set of 3 new tags: apex:remoteObjects, apex:remoteObjectModel, and apex:remoteObjectField.
For example, assume I want access to the Account object and that the Account object has a custom field named Custom__c on it. I want to be able to access the Id, Name, and Custom__c fields, and additionally rename the Custom__c field to just Custom so I don’t have to keep typing the __c. I could use the following code to accomplish this:
If you do not have any fields you want to rename, there is a short hand for specifying the fields you want:
Accessing the generated proxies
One important thing to note is the jsNamespace attribute on the remoteObjects tag, which controls the namespace of the generate JS objects. In our case, I set the jsNamespace = JSObjects, so when creating a new proxy instance I need to use that namespace. If you do not set the attribute, the default is SObjectModel.
To create objects, we can use code like:
Deleting objects is very similar in form:
The query object has to follow a specific format for the retrieve operation to work. You can find out more details about it on the documentation page. One thing to note here is that it appears you cannot traverse relationships in these queries like you can in SOQL.
For example I wanted to write the equivalent of:
Unfortunately, you cannot write this kind of where clause. If you do, you’ll get an error back from Salesforce about the query not being in the format you expect. This is mildly disappointing since it’s going to force developers to write more queries, which means pages will have more callbacks (reducing readability) and be chattier over the network.
If you want to just see a full page example of Remote Objects, check out this demo page which we’ve hosted on Github. If you find any mistakes or would like to expand on the demo, feel free to fork the repo and send us a pull request with your changes.