You need to sign in to do that
Don't have an account?
Nandhini S 3
Building Dynamic SOQL query
Hi Guys,
I have a method for which redord id is the input. So based on the ID we’ll get the object type and the queries will be built dynamically based on the object type. and based on the object field names should be added to the dynamic SOQL.
Example,
Select id, name from customObject__c where customfield__c =: recordID;
I have a method for which redord id is the input. So based on the ID we’ll get the object type and the queries will be built dynamically based on the object type. and based on the object field names should be added to the dynamic SOQL.
Example,
Select id, name from customObject__c where customfield__c =: recordID;
As you using this in Apex as a method with input record id, you can use following logic to get the object type: Once you get the object type you can write a SOQL to get the fields as well.
Hope above information helps. Please mark as Best Answer so that it can help others in future.
Thanks.
Thanks for your quick reply. I'm getting the object name by the way you have mentioned. The field in the where condition will vary based on the object. If the object is customObject1 then the field will be customfield1...for customObject2 the field will be customfield2. How can I get the fields like this.
Thanks for clarifying this.
You can utilize the DescribeSObjectResult Class for this as below: Here in above code you will need to put the object name received from first snippet instead of Account and you can get fields specific to object found with provided record id.
Reference:
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_sobject_describe.htm
Hope above information helps. Please mark as Best Answer so that it can help others in future.
Thanks.
DescribeSObjectResult is getting the details of the field not the field name.
For now, I have written the below to get the fieldName. Instead of hardcoding the fieldName, is there any way to get the field name.
String fieldName;
if (sObjName == 'Property__c') {
fieldName = 'Property__c';
}
else if (sObjName == 'Account') {
fieldName = 'Account__c';
}
string query = 'SELECT Id, Greatest_MRI_Vacate_Date__c FROM Lease__c WHERE' + fieldName + '=: recordId';