How can I get the Id of a record which has been inserted using Apex?
3 Answers
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;
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
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);
-
3welcome to the SF community. it is always good to elaborate your code with some explanation while adding as answer.– HimanshuCommented Jan 4, 2016 at 18:09
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 theafter insert
trigger.