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
John SamuelsJohn Samuels 

How can I pull in a fieldset across objects?

I have an Apex class that creates a graph based off of a fieldset. It originally pulled from an Account fieldset (let's say the fieldset is called TestFieldSet). Here is relevant code:

public RadarChartController(ApexPages.StandardController controller){
acctId = controller.getRecord().Id;
}


public List<Schema.FieldSetMember> getFields() {
system.debug(SObjectType.Account.FieldSets.TestFieldSet.getFields());
return SObjectType.Account.FieldSets.TestFieldSet.getFields();
}


public List<Map<Object,Object>> getData() {
String query = 'SELECT ';
List<String> fieldNames = new List<String>();


for(Schema.FieldSetMember f : getFields()){
query += f.getFieldPath() + ', ';
fieldNames.add(f.getFieldPath());
}
query += 'Id, Name FROM Account where Id=\'' + acctId + '\' LIMIT 1';


SObject myFieldResults = Database.Query(query);
Schema.DescribeSObjectResult R = myFieldResults.getSObjectType().getDescribe();
Map<String, Schema.SObjectField> fieldMap = R.fields.getmap();

However, I now want to pull a fieldset from another object. Call this TestFieldSet2. It is in custom object XYZ. However, the graph will still be displayed on an account record, so it needs to be associated with account ID in some way. I tried this code. Changes highlighted:

public RadarChartController(ApexPages.StandardController controller){
acctId = controller.getRecord().Id;
}


public List<Schema.FieldSetMember> getFields() {
system.debug(SObjectType.XYZ__c.FieldSets.TestFieldSet.getFields());
return SObjectType.XYZ__c.FieldSets.TestFieldSet.getFields();
}


public List<Map<Object,Object>> getData() {
String query = 'SELECT ';
List<String> fieldNames = new List<String>();


for(Schema.FieldSetMember f : getFields()){
query += f.getFieldPath() + ', ';
fieldNames.add(f.getFieldPath());
}
query += 'Id, Name FROM XYZ__c where Id=\'' + acctId + '\' LIMIT 1';


SObject myFieldResults = Database.Query(query);
Schema.DescribeSObjectResult R = myFieldResults.getSObjectType().getDescribe();
Map<String, Schema.SObjectField> fieldMap = R.fields.getmap();

This returns the error: "List has no rows for assignment to SObject". I'm pretty sure this is because of the part
where Id=\'' + acctId + '\' LIMIT 1';
I assume it isn't finding this because acctID doesn't exist in object XYZ. However, I'm not sure how to make the code display the correct data (that is associated with the account). Each record in XYZ has an associated account via look-up field, and I want to make sure that's the data that comes back. Any advice?

Thanks!

John SamuelsJohn Samuels
Sorry the formatting didn't work. Ignore the <u><em><strong> stuff.