function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shwetal DesaiShwetal Desai 

Get newly Inserted Record Id

I have one controller for my VF Page.
m doing insert operation from controller...
insert myobject;
now i want to fetch and set RecordId which is generated from this insert statement into one variable ("newId") in controller.
how can i do this?
Jon Mountjoy_Jon Mountjoy_
Hi Shwetal

Have you tried something like this:
 Rig__c r = new Rig__c(name='dance');
 insert r;
 result =;

ie. I just access the id.  Check out the Visualforce documentation - it has an example like that.  The Apex Language Reference also points out that insert returns a SaveResult array, which you can also use to retrieve the id.

Look here for the docs.

Shwetal DesaiShwetal Desai
Thanks Jon,
I got the ID...

Thanks & Regards,
Shwetal Desai
Carlos NaranjoCarlos Naranjo
Shwetal can you share what you did?
i'm trying to pas the id of an attachment right after inserting the attachment using apex. I want to get the id of the new attachment and insert this new id to a custom field right on the parent id page of this new attachment. Could you share please? 
Thanks on advanced! 
Anil kumar GorantalaAnil kumar Gorantala
position__c pos=new position__c();
insert pos;
id posid=pos.Id;
system.debug('Position Name: '+pos.Name+'Extracted Id of position is '+posid+' Extracted position name is '+posname);

now pass the 'posid' variable
Amit Kumar RaikwarAmit Kumar Raikwar

Instead of insert command use
Database.SaveResult[] srList = Database.insert(accts, false);
Database.SaveResult array contains the Ids of all the inserted records.

Account acc= new Account(Name='Company');
Database.Result[] result=Database.insert(acc);
List<Id> a;
for(Database.Result r:result){