3

I'd like to get straight exactly what is happening when I create an sObject in Force.com code but can't find any information on the specifics.

The Id is null until after the DML insert statement. Does this mean that the Id is being assigned as a result of a return value from the database?

This leads me to wonder if I could get more than one value back from the insert.

Is it possible to insert and then select back all of the automatically created fields such as Case.CaseNumber in one statement? Or is the sequence below (a DML insert followed by a SOQL SELECT to get specific fields) the only / correct way to do this?

Case c = new Case();

System.assert(c.Id == null);         // id not created on Case construction
System.assert(c.CaseNumber == null); 

insert c;

System.assert(c.Id != null);         // not null after insert
System.assert(c.CaseNumber == null); // still null after insert

c = [SELECT Id, CaseNumber FROM Case WHERE Id = :c.Id];

System.assert(c.Id != null);
System.assert(c.CaseNumber != null); // not null after select from database
1
  • There was a tweet from Rich Unger which basically said "mySobject.id = someId; #Spring13". It is hard to tell from that what is involved, but something in the assignment of Ids to sObjects will be changing in Spring 13. It may or may not relate to insertion. (Note I changed the quote from #Winter13 to #Spring13) Commented Nov 18, 2012 at 18:31

2 Answers 2

6

Yes the id is set on the sobject instance after the insert invocation, however none of the other fields are automatically available. (Unless youve explicitly set them on the sobject and they are not calculated fields) So whilst you can directly obtain the id from the sobject instance, for anything else, you will have to execute a soql query to select those fields, as you have in your example above.

Here's an excerpt from the documentation

The insert statement automatically sets the ID value of all new sObject records. Inserting a record that already has an ID—and therefore already exists in your organization's data—produces an error.

1
  • Good to clear that up, and thanks also for the link :)
    – Joe
    Commented Nov 18, 2012 at 15:32
2

As techtrekker said, you cannot provide ID while you insert a record. It will be created automatically by Salesfrce.

In Salesforce, the formula field/auto number field will be calculated only when a SOQL/SOSL query is executed.

That is the reason the CaseNumber field is null until SOQL query is executed.

The above method is the right way to go!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .