[SalesForce] Display fields only if the values are not null or blank for a dynamic SOQL Query

I stored all the editable fields in a variable and calling the variable in a dynamic SOQL query.
My Query:

String fieldApiList = String.join(fieldsApiNames, ',');
        query = 'SELECT Name,'+ fieldApiList +' from EP_Service_License__c WHERE ID IN:recordIdSet';
        
        SelectedEpserviceRecords=Database.query(query);  

Now, using a VF page I am displaying the fields and its values like as follows
enter image description here

my requirement is, if any field value is null or blank in the selected records or any field values is same in all the selected records then I should not display that field.
For example, here in the picture, product license number is same for all the selected records and Copy Primary Prod Co License(s) field is null for all the selected records. Now, I should avoid displaying those two in the output. This should happen dynamically for all the fields.

Kindly help me on this

Best Answer

With your fieldApiNames, you can check each field to see which values are returned:

String[] fieldsToDisplay = new String[0];
for(String fieldName: fieldApiNames) {
  Set<Object> values = new Set<Object>();
  for(sObject record: SelectedEpserviceRecords) {
    values.add(record.get(fieldName));
  }
  if(values.size() > 1) {
    fieldsToDisplay.add(fieldName);
  }
}

Then you'll be able to show only the fields that have at least two different values.

Related Topic