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
Odlin LOdlin L 

Variable text string for SObject get method?

I want to use a variable string rather than a hard-coded string in my get method.

For example, for every Field in Object A there will be a record in Object B and the record name is the field api name from Object A. I want to reference Object B's name in a Object A dynamic soql query.:
String fieldName = objectB.Name
Sobject objectA = Database.query('Select Id From ObjectA__c Where Id = \'' + ObjectB.Object_A_Id__c + '\' Limit 1');
objectB.Number_Field__c = (integer)objectA.get(fieldName);
​I don't know if this is possible. I get the error System.TypeException: Invalid conversion from runtime type Id to Integer. Still new to Apex coding.
LBKLBK
Hi Odlin,

Can you please post the complete ERD of ObjectA__c and ObjectB__c, with couple of sample records?

It will be a lot easier to help you, if we get to see real data.
Odlin LOdlin L
Hi LBK,

Thank you for responding and excuse the late reply!

The idea is for every one ObjectA__c record there will be as many ObjectB__c records as there are ObjectA__c fields (*.getDescribe().fields).

I'd like to store the value of each field in ObjectA__c record into each ObjectB__c record as it corresponds to the field in ObjectA__c.

i.e.
ObjectA__c  has three total custom fields and their api names are NumberField1__c, NumberField2__c, NumberField3__c.

A record in Object A is created: Name = 'ObjA-00001', NumberField1__c = 123, NumberField2__c = 456, NumberField3__c = 789

When those three fields are filled in, create three ObjectB__c records.

1st ObjectB Record: Name =  'NumberField1__c', Value__c = (value entered into NumberField1__c, in this case 123)
2nd ObjectB Record:  Name = 'NumberField2__c', Value__c = (value entere into NumberField2__c, in this case 456)
3rd ObjectB Record: Name = 'NumberField3__c', Value__c = (value entered into NumberField3__c, in this case 789)

If I create a new field NumberField4__c in ObjectA__c then when I create a new ObjectA__c record, I should then create 4 ObjectB records and so on. 


 
LBKLBK
I hope you have a worthy use case for this because you are going to consume a lot of data storage for storing data like this.

For example, for a record (with three number fields in ObjectA__c) you will be consuming 8 kb (2 kb in ObjectA__c and 6 kb in ObjectB__c) instead of just 2 kb.

Try the following code and let me know if it works for you.
 
String fieldName = (String)objectB.Name;
Sobject objectA = Database.query('Select Id, ' + fieldName +' From ObjectA__c Where Id = \'' + objectB.Object_A_Id__c + '\' Limit 1');
objectB.Value__c = (integer)objectA.get(fieldName);

My assumptions are here.

ObjectB.Object_A_Id__c - This is a Lookup field to ObjectA__c
ObjectB.Value__c is an Integer / Number type field.