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
Mak OneMak One 

I want to provide null value to fields dynamically. Means whatever fields have to be nullified will come from a List.

I have to do something like this:

Object__c obj;    //Initiated in Constructor
List<String> fieldNames=new List<String>{'Field1__c, Field2__c, Field3__c};

for (String str: fieldNames) {
obj.<str>=null
}
update obj;

So, it will be obj.Field1__c=null; obj.Field2__c=null ...

Can we do this in Salesforce Apex?
Best Answer chosen by Mak One
Tony TannousTony Tannous
You can do the below :

sObject sObj = Schema.getGlobalDescribe().get('Object__c').newSObject() ;

List<String> fieldNames=new List<String>{'Field1__c, Field2__c, Field3__c};

for (String str: fieldNames) {
sObj.put(str , null) ;
}

insert sObj;

Regards,

All Answers

Tony TannousTony Tannous
You can do the below :

sObject sObj = Schema.getGlobalDescribe().get('Object__c').newSObject() ;

List<String> fieldNames=new List<String>{'Field1__c, Field2__c, Field3__c};

for (String str: fieldNames) {
sObj.put(str , null) ;
}

insert sObj;

Regards,
This was selected as the best answer
Mak OneMak One
Thank You!

Directly
obj.put(str,null) is also working.