Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demo of Visualforce Remote Objects vs Remote Actions for blog post on the pros and cons
<apex:page controller="RemoteObjectDemoController">
<apex:remoteObjects >
<apex:remoteObjectModel name="WorkOrder__c" fields="Id,Name,AccountName__c,Cost__c"/>
<apex:remoteObjectModel name="WorkOrderLineItem__c" fields="Id,Name,Description__c,Hours__c,WorkOrder__c"/>
</apex:remoteObjects>
<script>
function doSomethingJS(answer)
{
// Create work order
var workOrder = new SObjectModel.WorkOrder__c();
workOrder.set('AccountName__c','Hitchhikers.com');
workOrder.set('Cost__c', answer * 100);
workOrder.create(function(error, result, event)
{
// Success? (seems to be null on success?)
if(error == null)
{
// Create work order line item
var workOrderLineItem = new SObjectModel.WorkOrderLineItem__c();
workOrderLineItem.set('Description__c', 'Answering the question');
workOrderLineItem.set('Hours__c', answer);
workOrderLineItem.set('WorkOrder__c', result[0]);
workOrderLineItem.create(function(error, result, event)
{
// Errors?
if(error!=null)
alert(error);
else
alert('Success');
} );
return;
}
// Display error
alert(error);
} );
}
function doSomethingApex(answer)
{
// Create work order and line item via Apex
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.RemoteObjectDemoController.doSomething}',
answer,
function(result, event){
alert(event.status ? 'Success' : event.message);
});
}
</script>
<p>
<span>What is the answer to life the universe and everything?</span>
</p>
<p>
<input id="answer" value="42"/>
</p>
<p>
<input type="button" value="Do Something (Apex)"
onclick="doSomethingApex(document.getElementById('answer').value);"/>
<input type="button" value="Do Something (JavaScript)"
onclick="doSomethingJS(document.getElementById('answer').value);"/>
</p>
</apex:page>
public with sharing class RemoteObjectDemoController
{
@RemoteAction
public static void doSomething(Integer answer)
{
WorkOrder__c workOrder = new WorkOrder__c();
workOrder.AccountName__c = 'Hitchhikers.com';
workOrder.Cost__c = answer * 100;
insert workOrder;
WorkOrderLineItem__c workOrderLineItem = new WorkOrderLineItem__c();
workOrderLineItem.Description__c = 'Answering the question';
workOrderLineItem.Hours__c = answer;
workOrderLineItem.WorkOrder__c = workOrder.Id;
insert workOrderLineItem;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment