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
IceEngineIceEngine 

How to use SObject Fields as parameter?

Hi!

I have a set of Fields should be update, please teach me how to do ,thanks!

 

Set<String> Fieldset = new Set<String>{'Fax','Website'};

account a1 = [select id,Fax,Website from account limit 1];
account a2 = [select id,Fax,Website from account limit 1 offset 1 ];

for (string Field1 : Fieldset ) {
     a1.Field1 = String.valueof(a2.Field1);       // Error : Invalid Field1 for SObject Account
     //update a1;
}

 

 

don't work in a loop

for(String field :fields)
{
accs[0].get(field) = accs[1].get(field); //Expression cannot be assigned (the get() Arguments should be Integer i) accs[0].field = accs[1].field; //Invalid field field for SObject Account }

and don't work just as a parameter

 

list<String> fields2 = new list<String>{'Fax','Website'};
accs[0].fields2[0] = accs[1].fields2[0];          //Invalid field fields2 for SObject Account

 

 can work when set  the exact Field Name

        accs[0].Fax = accs[1].Fax;   //List SObject Type
accs.Fax = accs.Fax; //SObject Type

 

 Regards

Best Answer chosen by Admin (Salesforce Developers) 
IceEngineIceEngine

Thank you Noam.dgani,

 

accs[0].get(field) = accs[1].get(field);  // Will turnout an Error :  Expression cannot be assigned

 

for sObject, This is correct :

a1.put ( field, a2.get (field) );

All Answers

kiranmutturukiranmutturu
what ever field that you are using it should be there in soql query account a2 = [select id,column1 from account where id ='002'];
IceEngineIceEngine

Still don't work , you can test the code below:


Set<String> Fieldset = new Set<String>{'Fax','Website'};

account a1 = [select id,Fax,Website from account limit 1];
account a2 = [select id,Fax,Website from account limit 1 offset 1];

for (string Field1 : Fieldset ) {
     a1.Field1 String.valueof(a2.Field1) ;       // Error : Invalid Field1 for SObject Account
     //update a1;
}





Noam.dganiNoam.dgani

Hi IceEngine

 

this has bad practice written all over it, but the following code will do what you wanted:

Set<String> fields = new Set<String>{'Fax','Website'};

String q = 'Select ';
for(String field : fields)
{
	q += field + ',';
}

q = q.subString(0.q.length()-1);
q += ' From Account limit 2';

List<Account> accs = Database.query(q);
for(String field :fields)
{
	accs[0].get(field) = accs[1].get(field);
}
update accs[0];

 

IceEngineIceEngine

Thank you Noam.dgani,

 

accs[0].get(field) = accs[1].get(field);  // Will turnout an Error :  Expression cannot be assigned

 

for sObject, This is correct :

a1.put ( field, a2.get (field) );

This was selected as the best answer
Noam.dganiNoam.dgani

yep.

 

right about the .put part.

 

glad to help