create()

Adds one or more new individual objects to your organization’s data.

Syntax

SaveResult[] = sfdc.create(sObject[] sObjects);

Usage

Use create() to add one or more individual objects, such as an Account or Contact, 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.

Permissions

Your client application must be logged in with sufficient access rights to create individual objects within the specified object. For more information, see Factors that Affect Data Access. In general, many permission issues can be circumvented by having the "Modify All Data" permission.

Special Handling

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 particular object, be sure to read its description in the Standard Objects.

Createable Fields

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.

Automatically Maintained Fields

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 object 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.

Required Fields

For required fields that do not have a preconfigured default value, you must supply a value. For more information, see Required Fields.

Default Values

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.

  • For required fields that do not have a preconfigured default value, you must supply a value.
  • For all other fields in the object, if you do not explicitly specify a value, then its value is null (VT_EMPTY).

Referential Integrity

Your client application must conform to the rules of referential integrity. For example, if you are creating 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 caseID for the parent Case, and that parent Case must exist in the database.

Valid Data Values

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).

String Values

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".

Assignment Rules

When creating new Account (accounts fire Territory Management assignment rules), Case, or Lead objects, 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.

Maximum Number of Objects Created

Your client application can add up to 200 individual objects in a single create() call. If a create request exceeds 200 objects, then the entire operation fails.

Relationships

Although you can use relationships in query() calls, you cannot create objects of different types even if they have a parent-child relationship, for example accounts and contacts.

create() and Foreign Keys

You can use external ID fields as a foreign key, allowing you to create, update, or upsert records in a single step instead of querying a record to get the ID first. To do this, specify the foreign key name and the external ID field value. For example:

Opportunity newOpportunity = new Opportunity();
newOpportunity.setStageName("Prospecting");
Account parentAccountRef = new Account();
parentAccountRef.setExternal_SAP1_ACCTID__c("SAP111111"); 
newOpportunity.setAccount(parentAccount);
SaveResult[] results = binding.create(new SObject[] {newOpportunity});

Basic Steps for Creating Objects

Creating objects involves the following basic steps:

  1. Instantiate one or more individual objects from the session. For each object, populate its fields with the data that you want to add.
  2. Construct an sObject[] array and populate that array with the objects that you want to create. All objects must be of the same type.
  3. Call create(), passing in the sObject[] array.
  4. Process the results in the SaveResult[] object to verify whether the objects have been successfully created.

Sample Code—Java

public Boolean createAccountSample()
{
 // Create two account objects   
 Account account1 = new Account();
  Account account2 = new Account();

 // Set some fields on the account object
  // Name field (required) not being set on account1,
  // so this record should fail during create.
  account1.setAccountNumber("002DF99ELK9");
  account1.setBillingCity("Wichita");
  account1.setBillingCountry("US");
  account1.setBillingState("KA");
  account1.setBillingStreet("4322 Haystack Boulevard");
  account1.setBillingPostalCode("87901");

 // Set some fields on the account2 object
  account2.setName("Golden Straw");
  account2.setAccountNumber("003DF99ELK9");
  account2.setBillingCity("Oakland");
  account2.setBillingCountry("US");
  account2.setBillingState("CA");
  account2.setBillingStreet("666 Raiders Boulevard");
  account2.setBillingPostalCode("97502");

 // Create an array of SObjects to hold the accounts
  SObject[] sObjects = new SObject[2];
  // Add the accounts to the SObject array
  sObjects[0] = account1;
  sObjects[1] = account2;

 // Invoke the create call
 try {
    SaveResult[] saveResults = binding.create(sObjects);

    // Handle the results
    for (int i=0; i<saveResults.length; i++) {
      // Determine whether create succeeded or had errors
     if (saveResults[i].isSuccess()) {
        // No errors, so we will retrieve the id created for this index
       System.out.println(saveResults[i].getId());
      }
      else {
        // Handle the errors
        ...
      }
    }
  } catch (InvalidSObjectFault e) {
    System.out.println("Invalid object exception encountered:\n\n" + e.getMessage());
    return Boolean.FALSE;
  } catch (UnexpectedErrorFault e) {
    System.out.println("Unexpected error exception encountered:\n\n" + e.getMessage());
    return Boolean.FALSE;
  } catch (InvalidIdFault e) {
    System.out.println("Invalid Id exception encountered:\n\n" + e.getMessage());
    return Boolean.FALSE;
  } catch (RemoteException e) {
    System.out.println("Remote exception encountered:\n\n" + e.getMessage());
    return Boolean.FALSE;
  }
  return Boolean.TRUE;
}

Sample Code—C#

using System;
using System.Collections.Generic;
using System.Text;
using SFDCWsdl.Salesforce_WSDL;

namespace SFDCWsdl
{
    public class SFDCWsdlTest
    {
        private SforceService binding;

        private static readonly string Username = "USERNAME";
        private static readonly string Password = "PASSWORD";

        /// <summary>
        /// Create the binding and login
        /// </summary>
        private SFDCWsdlTest()
        {
            this.binding = new SforceService();
            binding.login(SFDCWsdlTest.Username, SFDCWsdlTest.Password);
        }

        private void CreateAccountSample()
        {
            sObject account;
            sObject[] accs = new sObject[1];

            account = new sObject();
            System.Xml.XmlElement[] acct = new System.Xml.XmlElement[6];

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            acct[0] = doc.CreateElement("Industry"); acct[0].InnerText = "Farming";
            acct[1] = doc.CreateElement("Name"); acct[1].InnerText = "Golden Straw";
            acct[2] = doc.CreateElement("NumberOfEmployees"); acct[2].InnerText = "40";
            acct[3] = doc.CreateElement("Ownership"); acct[3].InnerText = "Privately Held";
            acct[4] = doc.CreateElement("Phone"); acct[4].InnerText = "666.666.6666";
            acct[5] = doc.CreateElement("Website"); acct[5].InnerText = "www.oz.com";
            account.type = "Account";
            account.Any = acct;
            accs[0] = account;

            //create the object(s) by sending the array to the API
            SaveResult[] sr = binding.create(accs);
            for (int j = 0; j < sr.Length; j++)
            {
                if (sr[j].success)
                {
                    Console.Write(System.Environment.NewLine + 
                        "An account was created with an id of: " + sr[j].id);
                }
                else
                {
                    //there were errors during the create call, go through the errors
                    //array and write them to the screen
                    for (int i = 0; i < sr[j].errors.Length; i++)
                    {
                        //get the next error
                        Error err = sr[j].errors[i];
                        Console.WriteLine("Errors were found on item " + j.ToString());
                        Console.WriteLine("Error code is: " + err.statusCode.ToString());
                        Console.WriteLine("Error message: " + err.message);
                    }
                }
            }
        }
    }
}

Arguments

Name Type Description
sObjects sObject[] Array of one or more sObject to create(). Limit: 200 sObjects.

Response

SaveResult[]

Faults

InvalidSObjectFault

UnexpectedErrorFault

See Also:
upsert()
API Call Basics
https://wiki.apexdevnet.com/index.php/Sample_SOAP_Messages
© Copyright 2000-2008 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.