You need to sign in to do that
Don't have an account?
kumarm009
Inserting Custom Object in Apex code
Hi,
I am looking for a way to insert custom object in Database in Apex code.
I am able to compute the column values of the row but not able to figure out how to create this custom object instance and store in database.
Thanks for the Help.
// Create an in-memory SObject
CustomObject__c myCustomObject = new CustomObject__c (
name = 'foobar', customField__c = 'zap'
);
// Insert it into the database
insert myCustomObject;
// View its content, including ID (null until it's inserted)
system.debug( myCustomObject );
// Display a URL which you can cut and paste into your browser to see the detail page for the inserted object
String urlForDetailPage = new PageReference('/' + myCustomObject.id).getUrl();
system.debug( urlForDetailPage );
(edited in firefox because Safari 3 /osx always breaks code insertions)
All Answers
// Create an in-memory SObject
CustomObject__c myCustomObject = new CustomObject__c (
name = 'foobar', customField__c = 'zap'
);
// Insert it into the database
insert myCustomObject;
// View its content, including ID (null until it's inserted)
system.debug( myCustomObject );
// Display a URL which you can cut and paste into your browser to see the detail page for the inserted object
String urlForDetailPage = new PageReference('/' + myCustomObject.id).getUrl();
system.debug( urlForDetailPage );
(edited in firefox because Safari 3 /osx always breaks code insertions)
Shikibu,
Do I need to do any commit operation? I can see that data is inserted in the session but if i query through Apex Explorer, I don't see the same data.
Thanks for the Help.
kumarm009, "insert" is a commit.
I don't use Apex Explorer, but did you try using the url that the code I provided would print for you? You should be able to see the newly inserted (commited) object via the Salesforce UI.
Or, use the line in the code that I provided that shows you the Id, and use that to find the object in Apex Explorer.
Or, use Apex Explorer to display a list of most recently created CustomObject__c, order by createddate desc.
If I try to access the page, I am getting error message "Data Not Available -
The data you were trying to access could not be found. It may be due to another user deleting the data or a system error. If you know the data is not deleted but cannot access it, please look at our support page."
But from the debug log I can see the object was created since id was provided. Its just that I am not able to see the data.
This may be far-fetched, but is your insert code running inside a testmethod? If so, the data will seem to be committed, but will vanish when the testmethod completes.
Have you tried inserting a standard object? I see you are relatively new to the forums, but don't know if you are also just starting to learn apex.
Shikibu,
Yes I was inserting code from test method and forgot that data gets deleted after the test.
Thanks for the help.