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
Laxman RaoLaxman Rao 

How to update sObject Dynamically?

Hi ,

 

When i try to update the sobject dynamically it throws me a error saying "System.SObjectException: Field Id is not editable". Can you please help on this:

 

I have used the below code to update :


Schema.SObjectType t = Schema.getGlobalDescribe().get('Account');
SObject sObjectAccount = t.newSObject();
sObjectAccount.put('Id', '001G000000pyDGL');
sObjectAccount.put('Name', 'Test');

Update sObjectAccount;

Best Answer chosen by Admin (Salesforce Developers) 
Laxman RaoLaxman Rao

thanks for replying.

 

If we remove the Id it will insert the record, I want the record to update.

 

I have queried the corresponding record from Account and I have updated using this :

String query = 'Select Id From Account Where Id = \'001G000000pyDGL\'';
system.debug(query );
Sobject sObjectAccount = Database.Query(query);
sObjectAccount.put('Name', 'Test.');

All Answers

MagulanDuraipandianMagulanDuraipandian

You cannot edit or set ID field.


Remove sObjectAccount.put('Id', '001G000000pyDGL');

 

Cheers !!!

 

Regards,

Magulan D

Salesforce.com certified Force.com Developer.

 

SFDC Blog

 

If this post is your solution, kindly mark this as the solution.

Laxman RaoLaxman Rao

thanks for replying.

 

If we remove the Id it will insert the record, I want the record to update.

 

I have queried the corresponding record from Account and I have updated using this :

String query = 'Select Id From Account Where Id = \'001G000000pyDGL\'';
system.debug(query );
Sobject sObjectAccount = Database.Query(query);
sObjectAccount.put('Name', 'Test.');

This was selected as the best answer
BritishBoyinDCBritishBoyinDC

You don't need to query the record - you can do this:

 

Schema.SObjectType t = Schema.getGlobalDescribe().get('Account');
SObject sObjectAccount = t.newSObject('0013000001Ablpu');
sObjectAccount.put('Name', 'Test Update 4');
Update sObjectAccount;

 

Laxman RaoLaxman Rao

Hi,

 

Thanks for the solution.