Newer Version Available

This content describes an older version of this product. View Latest

Working with Salesforce Records

It’s easy to work with your Salesforce records in Apex.

The term sObject refers to any object that can be stored in Force.com. This could be a standard object, such as Account, or a custom object that you create, such as a Merchandise object.

An sObject variable represents a row of data, also known as a record. To work with an object in Apex, declare it using the SOAP API name of the object. For example:

1swfobject.registerObject("clippy.codeblock-0", "9");Account a = new Account();
2MyCustomObject__c co = new MyCustomObject__c();

For more information on working on records with Apex, see Working with Data in Apex.

This example controller persists an updated Account record. Note that the update method has the @AuraEnabled annotation, which enables it to be called as a server-side controller action.

1swfobject.registerObject("clippy.codeblock-1", "9");public class AccountController {
2
3    @AuraEnabled
4    public static void updateAnnualRevenue(String accountId, Decimal annualRevenue) {
5        Account acct = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :accountId];
6        acct.AnnualRevenue = annualRevenue;
7        update acct;
8    }
9}

For an example of calling Apex code from JavaScript code, see the Quick Start.

Loading Record Data from a Standard Object

Load records from a standard object in a server-side controller. The following server-side controller has methods that return a list of opportunity records and an individual opportunity record.
1swfobject.registerObject("clippy.codeblock-2", "9");public class OpportunityController {
2
3    @AuraEnabled
4    public static List<Opportunity> getOpportunities() {
5        List<Opportunity> opportunities = 
6                [SELECT Id, Name, CloseDate FROM Opportunity];
7        return opportunities;
8    }
9
10    @AuraEnabled
11    public static Opportunity getOpportunity(Id id) {
12        Opportunity opportunity = [
13                SELECT Id, Account.Name, Name, CloseDate, 
14                       Owner.Name, Amount, Description, StageName
15            FROM Opportunity
16            WHERE Id = :id
17         ];
18        return opportunity;
19    }
20}
This example component uses the previous server-side controller to display a list of opportunity records when you press a button.
1<aura:component controller="OpportunityController">
2    <aura:attribute name="opportunities" type="Opportunity[]"/>
3    
4    <ui:button label="Get Opportunities" press="{!c.getOpps}"/>
5    <aura:iteration var="opportunity" items="{!v.opportunities}">
6    	<p>{!opportunity.Name} : {!opportunity.CloseDate}</p>
7    </aura:iteration>
8</aura:component>
When you press the button, the following client-side controller calls the getOpportunities() server-side controller and sets the opportunities attribute on the component. For more information about calling server-side controller methods, see Calling a Server-Side Action.
1({
2    getOpps: function(cmp){
3        var action = cmp.get("c.getOpportunities");
4        action.setCallback(this, function(response){
5            var state = response.getState();
6            if (state === "SUCCESS") {
7                cmp.set("v.opportunities", response.getReturnValue());
8            }
9        });
10	 $A.enqueueAction(action);
11    }
12})

To load record data during component initialization, use the init handler.

Note

Loading Record Data from a Custom Object

Load record data using an Apex controller and setting the data on a component attribute. This server-side controller returns records on a custom object myObj__c.
1swfobject.registerObject("clippy.codeblock-5", "9");public class MyObjController {
2    
3    @AuraEnabled
4    public static List<MyObj__c> getMyObjects() {
5        return [SELECT Id, Name, myField__c FROM MyObj__c];
6    }
7}

This example component uses the previous controller to display a list of records from the myObj__c custom object.

1swfobject.registerObject("clippy.codeblock-6", "9");<aura:component controller="MyObjController"/>
2<aura:attribute name="myObjects" type="namespace.MyObj__c[]"/>
3<aura:iteration items="{!v.myObjects}" var="obj">
4    {!obj.Name}, {!obj.namespace__myField__c}
5</aura:iteration>
This client-side controller sets the myObjects component attribute with the record data by calling the getMyObjects() method in the server-side controller. This step can also be done during component initialization using the init handler.
1swfobject.registerObject("clippy.codeblock-7", "9");getMyObjects: function(cmp){
2    var action = cmp.get("c.getMyObjects");
3    action.setCallback(this, function(response){
4        var state = response.getState();
5        if (state === "SUCCESS") {
6            cmp.set("v.myObjects", a.getReturnValue());
7        }
8    });
9    $A.enqueueAction(action);
10}

For an example on loading and updating records using controllers, see the Quick Start.

Saving Your Record Data

You can take advantage of the built-in create and edit record pages in Salesforce1 to create or edit records via a Lightning component. For example, the following component contains a button that calls a client-side controller to display the edit record page.
1<aura:component>
2    <ui:button label="Edit Record" press="{!c.edit}"/>
3</aura:component>
The client-side controller fires the force:recordEdit event, which displays the edit record page for a given contact ID. For this event to be handled correctly, the component must be included in Salesforce1.
1edit : function(component, event, helper) {
2    var editRecordEvent = $A.get("e.force:editRecord");
3    editRecordEvent.setParams({
4        "recordId": component.get("v.contact.Id")
5    });
6    editRecordEvent.fire();
7}

Records updated using the force:recordEdit event are persisted by default.

Alternatively, you might have a Lightning component that provides a custom form for users to add a record. To save the new record, wire up a client-side controller to an Apex controller. The following list shows how you can persist a record via a component and Apex controller.

If you create a custom form to handle record updates, you must provide your own field validation.

Note

  • Create an Apex controller to save your updates with the upsert operation. The following example is an Apex controller for upserting record data.
    1@AuraEnabled
    2public static Expense__c saveExpense(Expense__c expense) {
    3    upsert expense;
    4    return expense;
    5}
  • Call a client-side controller from your component. For example, <ui:button label="Submit" press="{!c.createExpense}"/>.
  • In your client-side controller, get an instance of the server-side controller and set a callback. The following example upserts a record on a custom object. Recall that setParams() sets the value of the expense argument on the server-side controller’s saveExpense() method.
    1upsertExpense : function(component, expense, callback) {
    2      var action = component.get("c.saveExpense");
    3      action.setParams({ 
    4          "expense": expense
    5      });
    6      if (callback) {
    7          action.setCallback(this, callback);
    8      }
    9      $A.enqueueAction(action);
    10    }