Tuesday 12 February 2013

How To Rewrite ID of Any Record in Salesforce


Recently I came up with a new feature of Spring 13 as you could not set Id field after creating record but now you can.
You can set the Id field on the any Sobjects to IDs of  any other existing record using update DML. Here we will learn how to do this and what are benefits of this feature.
In following example we are creating two new record of Account object. TestAccount1 & TestAccount2.

// Insert both accounts
Account TestAccount1 = new Account(Name='Account1');
insert TestAccount1 ;
Account TestAccount2= new Account(Name='Account2', Industry='Energy');
insert TestAccount2 ; 
// fetching first Account to update
TestAccount1 = [select id,Name,industry from Account where id = : TestAccount1.id ] ;
// Update the first account.
TestAccount2.Id = TestAccount1.Id;
update TestAccount2;
after performing above execution You will find that TestAccount1's industry & Account Name will be updated from TestAccount2 record.

But if we do as below :
TestAccount1 = [select id,Name from Account where id = : TestAccount1.id ] ;
// Update the first account.
TestAccount2.Id = TestAccount1.Id;
update TestAccount2;
then only name will be update from TestAccount2 not industry field.

No comments:

Post a Comment