11

How can I get the Id of a record which has been inserted using Apex?

  • 1
    Can you please elaborate your question? If you are using statement like "insert account", the Id of the account can be accessed by "account.Id". – Vignex Nov 26 '14 at 9:12
  • better if you can share your code – highfive Nov 26 '14 at 10:48
  • If by chance you are using triggers and are wondering where the id is on a before insert trigger, it is not available as the record is not yet saved. You will only be able to access the id on an insert event within the after insert trigger. – cropredy Nov 26 '14 at 18:00
  • This question has been re-asked multiple times. If there's an FAQ, this deserves to be on it. – Foo Bar Dec 13 '19 at 14:32
12

The platform allocates an ID value and sets it in an SObject's ID field implicitly as part of the insert operation:

Account a  = new Account(Name = 'Acme');
// a.Id is null here

insert a;
// a.Id now has a value set by the platform

Fields are accessed using just a dot and the field name; there isn't a corresponding getId() method. (The generic field get method does work for 'Id'.)

So most of the time you do not assign a value to an object's ID field. An exception is where you have the ID of the object (perhaps from a lookup field on a different object) and want to update the object. In that case you can assign the ID and so save having to first query the object:

Account a = new Account(Id = accountId, Name = 'New Name');
update a;
7

If you are using statement like "insert account;", the Id of the account can be accessed by "account.Id;". Below code will give you an overview.

Account acct = new Account(Name='SFDC Account');
insert acct;

system.debug("Inserted Account Id = "+acct.Id);

acct.Id will provide the Id for the Account record acct.The debug statement above will write the Id to the Debug logs.

Please visit the below link for DML usage and using Id for subsequent logic(s) : http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_dml_examples_insert_update.htm

-1
Account acct = new Account();
acct.put('Name', 'Test');
Id AccountId;

Database.SaveResult[] srList = Database.insert(acct);

for (Database.SaveResult sr : srList)
{
    AccountId = sr.getId();
}

System.debug(AccountId);
  • 1
    welcome to the SF community. it is always good to elaborate your code with some explanation while adding as answer. – Himanshu Jan 4 '16 at 18:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.