Adds one or more new records to your organization’s data.
SaveResult[] = connection.create(sObject[] sObjects);
Use create() to add one or more records, such as an Account or Contact record, to your organization’s information. The create() call is analogous to the INSERT statement in SQL.
When creating objects, consider the following rules and guidelines.
Your client application must be logged in with sufficient access rights to create records within the specified object. For more information, see Factors that Affect Data Access.
Certain objects—and certain fields within those objects—require special handling or permissions. For example, you might also need permissions to access the object’s parent object. Before you attempt to create() a record for a particular object, be sure to read its description in the Standard Objects.
Only objects where createable is true can be created via the create() call. To determine whether a given object can be created, your client application can invoke the describeSObjects() call on the object and inspect its createable property.
The API generates unique values for ID fields automatically. For create(), you cannot explicitly specify an ID value in the sObject. The SaveResult[] object contains the ID of each record that was successfully created. For information on IDs, see ID Field Type.
The API populates certain fields automatically, such as CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, and SystemModstamp. You cannot explicitly specify these values.
For required fields that do not have a preconfigured default value, you must supply a value. For more information, see Required Fields.
For some objects, some fields have a default value, such as OwnerID. If you do not specify a value for such fields, the API populates the fields with the default value. For example, if you do not override OwnerID, then the API populates this field with the user ID associated with the user as whom your client application is logged in.
Your client application must conform to the rules of referential integrity. For example, if you are creating a record for an object that is the child of a parent object, you must supply the foreign key information that links the child to the parent. For example, when creating a CaseComment, you must supply the valid case ID for the parent Case, and that parent Case must exist in the database.
You must supply values that are valid for the field’s data type, such as integers (not alphabetic characters) for integer fields. In your client application, follow the data formatting rules specified for your programming language and development tool (your development tool will handle the appropriate mapping of data types in SOAP messages).
When storing values in string fields, the API trims any leading and trailing whitespace. For example, if the value of a name field is entered as " ABC Company ", then the value is stored in the database as "ABC Company".
Starting with API version 15.0, if you specify a value for a field that contains a string, and the value is too big for the field, the call fails and an error is returned. In previous versions of the API the value was truncated and the call succeeded. If you wish to keep the old behavior with versions 15.0 and later, use the AllowFieldTruncationHeader SOAP header.
When creating new Account (accounts fire Territory Management assignment rules), Case, or Lead records, your client application can set options in the AssignmentRuleHeader to have the case or lead automatically assigned to one or more users based on assignment rules configured in the Salesforce user interface.
Your client application can add up to 200 records in a single create() call. If a create request exceeds 200 objects, then the entire operation fails.
The AllOrNoneHeader header allows you to roll back all changes unless all records are processed successfully. This header is available in API version 20.0 and later. The default behavior is to allow partial success of a call: records without errors are committed, while records with errors are marked as failed in the call results.
To subscribe to records they create, users must enable the Automatically follow records that I create option in their personal settings. If users have automatic subscriptions enabled, they automatically follow the records they create and see changes to those records in their Chatter feed on the Home tab.
A user can subscribe to a record or to another user. Changes to the record and updates from the users are displayed in the Chatter feed on the user's home page, which is a useful way to stay up-to-date with other users and with changes made to records in Salesforce. Feeds are available in API version 18.0 and later. The EntitySubscription object represents a subscription of a user following a record or another user.
If you're processing a large number of records and don't want to track the changes in various feeds related to the records, use DisableFeedTrackingHeader. This is especially useful for bulk changes.
You can create records for multiple object types, including custom objects, in one call with API version 20.0 and later. For example, you could create a contact and an account in one call. You can create records for up to 10 object types in one call.
Records are saved in the same order that they are entered in the sObjects input array. If you are entering new records that have a parent-child relationship, the parent record must precede the child record in the sObjects array. For example, if you are creating a contact that references an account that is also being created in the same call, the account must have a smaller index in the sObjects array than the contact does. The contact references the account by using an External ID field.
You can't add a record that references another record of the same object type in the same call. For example, the Contact object has a Reports To field that is a reference to another contact. You can't create two contacts in one call if one contact uses the Reports To field to reference a second contact in the sObjects array. You can create a contact that references another contact that has been previously created.
Records for different object types are broken into multiple chunks by Salesforce. A chunk is a subset of the sObjects input array and each chunk contains records of one object type. Data is committed on a chunk-by-chunk basis. Any Apex triggers related to the records in a chunk are invoked once per chunk. Consider an sObjects input array containing the following set of records:
Salesforce splits the records into five chunks:
Each call can process up to 10 chunks. If the sObjects array contains more than 10 chunks, you must process the records in more than one call.
You can use external ID fields as a foreign key, which allows you to create a record and relate it to another existing record in a single step instead of querying the parent record ID first. To do this, set the foreign key field to an instance of the parent sObject that only has the external ID field specified. This external ID should match the external ID value on the parent record.
The following Java and C# examples show you how to create an opportunity and relate it to an existing account using a custom external ID field named MyExtId__c. Each example creates an opportunity, sets the required fields, and then sets the opportunity external ID field to the account object that has only the external ID field specified. The code then creates the opportunity. Once the opportunity is created, the account will be its parent.
Java Example
public void createForeignKeySample() { try { Opportunity newOpportunity = new Opportunity(); newOpportunity.setName("OpportunityWithFK"); newOpportunity.setStageName("Prospecting"); Calendar dt = connection.getServerTimestamp().getTimestamp(); dt.add(Calendar.DAY_OF_MONTH, 7); newOpportunity.setCloseDate(dt); Account parentAccountRef = new Account(); parentAccountRef.setMyExtId__c("SAP1111111"); newOpportunity.setAccount(parentAccountRef); SaveResult[] results = connection .create(new SObject[] { newOpportunity }); } catch (ConnectionException ce) { ce.printStackTrace(); } }
C# Example
public void createForeignKeySample() { try { Opportunity newOpportunity = new Opportunity(); newOpportunity.Name = "OpportunityWithFK"; newOpportunity.StageName = "Prospecting"; DateTime dt = (DateTime)binding.getServerTimestamp().timestamp; newOpportunity.CloseDate = dt.AddDays(7); newOpportunity.CloseDateSpecified = true; // Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields Account accountReference = new Account(); accountReference.MyExtId__c = "SAP1111111"; newOpportunity.Account = accountReference; // Create the account and the opportunity SaveResult[] results = binding.create(new sObject[] { newOpportunity }); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } }
The parent and child records are records related through a predefined relationship, such as a master-detail or lookup relationship. You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types.
The following Java and C# examples show you how to create an opportunity with a parent account in the same create() call. Each example creates an Opportunity sObject and populates some of its fields, then creates two Account objects. The first account is only for the foreign key relationship, and the second is for the account creation and has the account fields set. Both accounts have the external ID field, MyExtID__c, set. Next, the sample calls create() by passing it an array of sObjects. The first element in the array is the parent sObject and the second is the opportunity sObject. The create() call creates the opportunity with its parent account in a single call. Finally, the sample checks the results of the call and writes the IDs of the created records to the console, or the first error if record creation fails.
Java Example
public void createForeignKeySample() { try { Opportunity newOpportunity = new Opportunity(); newOpportunity.setName("OpportunityWithAccountInsert"); newOpportunity.setStageName("Prospecting"); Calendar dt = connection.getServerTimestamp().getTimestamp(); dt.add(Calendar.DAY_OF_MONTH, 7); newOpportunity.setCloseDate(dt); // Create the parent reference. // Used only for foreign key reference // and doesn't contain any other fields. Account accountReference = new Account(); accountReference.setMyExtID__c("SAP111111"); newOpportunity.setAccount(accountReference); // Create the Account object to insert. // Same as above but has Name field. // Used for the create call. Account parentAccount = new Account(); parentAccount.setName("Hallie"); parentAccount.setMyExtID__c("SAP111111"); // Create the account and the opportunity. SaveResult[] results = connection.create(new SObject[] { parentAccount, newOpportunity }); // Check results. for (int i = 0; i < results.length; i++) { if (results[i].isSuccess()) { System.out.println("Successfully created ID: " + results[i].getId()); } else { System.out.println("Error: could not create sobject " + "for array element " + i + "."); System.out.println(" The error reported was: " + results[i].getErrors()[0].getMessage() + "\n"); } } } catch (ConnectionException ce) { ce.printStackTrace(); } }
C# Example
public void createForeignKeySample() { try { Opportunity newOpportunity = new Opportunity(); newOpportunity.Name = "OpportunityWithAccountInsert"; newOpportunity.StageName = "Prospecting"; DateTime dt = (DateTime)binding.getServerTimestamp().timestamp; newOpportunity.CloseDate = dt.AddDays(7); newOpportunity.CloseDateSpecified = true; // Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields. Account accountReference = new Account(); accountReference.MyExtID__c = "SAP111111"; newOpportunity.Account = accountReference; // Create the Account object to insert.
// Same as above but has Name field.
// Used for the create call. Account parentAccount = new Account(); parentAccount.Name = "Hallie"; parentAccount.MyExtID__c = "SAP111111"; // Create the account and the opportunity. SaveResult[] results = binding.create(new sObject[] { parentAccount, newOpportunity }); // Check results.
for (int i = 0; i < results.Length; i++) { if (results[i].success) { Console.WriteLine("Successfully created ID: " + results[i].id); } else { Console.WriteLine("Error: could not create sobject " + "for array element " + i + "."); Console.WriteLine(" The error reported was: " + results[i].errors[0].message + "\n"); } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } }
Creating records involves the following basic steps:
This sample shows how to create records. It creates two Account objects and sets their fields. The Name of the second account isn’t set so that an error occurs on creation, since Name is a required field. After making the create() call by passing the array containing the two accounts, the sample iterates over the results and writes the ID of the new account or an error message if the account creation fails. Finally, the sample returns an array of the new account IDs, which in this case contains only one ID.
public String[] createRecords() { // Create two accounts String[] result = new String[2]; Account account1 = new Account(); Account account2 = new Account(); // Set some fields on the account object account1.setName("The Brick Hut"); account1.setBillingStreet("403 McAdoo St"); account1.setBillingCity("Truth or Consequences"); account1.setBillingState("NM"); account1.setBillingPostalCode("87901"); account1.setBillingCountry("US"); // Required Name field is not being set on account2, // so this record should fail during create. // account2.setName("Camp One Creations"); account2.setBillingStreet("25800 Arnold Dr"); account2.setBillingCity("Sonoma"); account2.setBillingState("CA"); account2.setBillingPostalCode("95476"); account2.setBillingCountry("US"); Account[] accounts = { account1, account2 }; try { // Call create() to add the accounts SaveResult[] saveResults = connection.create(accounts); // Iterate through the results. // There should be one successful creation // and one failed creation. for (int i = 0; i < saveResults.length; i++) { if (saveResults[i].isSuccess()) { System.out.println("Successfully created Account ID: " + saveResults[i].getId()); result[i] = saveResults[i].getId(); } else { System.out.println("Error: could not create Account " + "for array element " + i + "."); System.out.println(" The error reported was: " + saveResults[i].getErrors()[0].getMessage() + "\n"); result[i] = saveResults[i].getId(); } } } catch (ConnectionException ce) { ce.printStackTrace(); } return result; }
This sample shows how to create records. It creates two Account objects and sets their fields. The Name of the second account isn’t set so that an error occurs on creation, since Name is a required field. After making the create() call by passing the array containing the two accounts, the sample iterates over the results and writes the ID of the new account or an error message if the account creation fails. Finally, the sample returns an array of the new account IDs, which in this case contains only one ID.
public String[] createRecords() { // Create two accounts String[] result = new String[2]; Account account1 = new Account(); Account account2 = new Account(); // Set some fields on the account object account1.Name = "The Brick Hut"; account1.BillingStreet = "403 McAdoo St"; account1.BillingCity = "Truth or Consequences"; account1.BillingState = "NM"; account1.BillingPostalCode = "87901"; account1.BillingCountry = "US"; // Required Name field is not being set on account2,
// so this record should fail during create.
// account2.Name = "Camp One Creations"; account2.BillingStreet = "25800 Arnold Dr"; account2.BillingCity = "Sonoma"; account2.BillingState = "CA"; account2.BillingPostalCode = "95476"; account2.BillingCountry = "US"; Account[] accounts = { account1, account2 }; try { // Call create() to add the accounts SaveResult[] saveResults = binding.create(accounts); // Iterate through the results.
// There should be one successful creation
// and one failed creation.
for (int i = 0; i < saveResults.Length; i++) { if (saveResults[i].success) { Console.WriteLine("Successfully created Account ID: " + saveResults[i].id); result[i] = saveResults[i].id; } else { Console.WriteLine("Error: could not create Account " + "for array element " + i + "." ); Console.WriteLine(" The error reported was: " + saveResults[i].errors[0].message + "\n"); result[i] = saveResults[i].id; } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } return result; }
| Name | Type | Description |
|---|---|---|
| sObjects | sObject[] | Array of one or more sObject objects to create(). Limit: 200 sObject values. |