Newer Version Available

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

Creating Records with Remote Objects

Create a record by calling create() on a Remote Objects model instance.
create() accepts two arguments, both optional.
1RemoteObjectModel.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.
1var ctDetails = { FirstName: 'Marc', LastName: 'Benioff' };
2
3// Call create() on an existing Contact model, with no arguments
4var ct = new RemoteObjectModel.Contact(ctDetails);
5ct.create();
6
7// Call create() on an empty Contact model, passing in field values
8var ct = new RemoteObjectModel.Contact();
9ct.create(ctDetails);
create() doesn’t return a result directly. The callback function enables you to handle the server response asynchronously.

All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being completed, including handling returned results, must be placed in the callback function.

Note

Your callback function can accept up to three arguments.
1function callback(Error error, Array results, Object event) { // ... }
See Remote Objects Callback Functions for details about writing Remote Objects callback functions.
The Id field is set on the Remote Object as part of a successful create() call. You can access this field in your callback function.
1var ctDetails = { FirstName: 'Marc', LastName: 'Benioff' };
2var ct = new RemoteObjectModel.Contact();
3ct.create(ctDetails, function(err) {
4    if(err) { 
5        console.log(err);
6        alert(err.message);
7    }
8    else {
9        // this is the contact
10        console.log(ct.log());     // Dump contact to log
11        console.log(ct.get('Id')); // Id is set when create completes
12    }
13});
Note the use of the log() function; it’s the equivalent of toString() for Remote Objects.

For clarity, this example uses a global variable, ct, which isn’t a best practice. See Remote Objects Callback Functions for better techniques.

Note