[SalesForce] Schema fields getMap() doesn’t return all the fields

I'm using Schema to retreive the fields and put them in a map that I can use in my Visualforce page.

public Map<String,String> m1{get;set;}
public List<String> fieldsList {get; set;} 

Schema.DescribeSObjectResult oppDescribe = T1_Passif__c.sObjectType.getDescribe();
Map<String, Schema.SObjectField> fields = oppDescribe.fields.getMap();
                for (Schema.SObjectField field: fields.values())
                {
                    Schema.DescribeFieldResult dr = field.getDescribe();
                    if(dr.isCustom())
                    {
                        if(obj.get(field)==null)
                        {
                        m1.put(field.getDescribe().getLabel(),'');
                        }
                        else
                        {                        
                        m1.put(field.getDescribe().getLabel(),String.valueOf(obj.get(field)));
                        }
                    }
                }
//add their labels to a list to maintain an order
FieldsList.add('Capital social ou personnel (1)');
FieldsList.add('Moins: actionnaires'); 

visualforce:

<apex:pageBlockTable value="{!fieldsList}" var="dirKey">
        <apex:column >

                <apex:outputText value="{!dirKey}" />
            <apex:facet name="header"><div align="center"> PASSIF </div></apex:facet>
        </apex:column>
        <apex:column style="text-align:center">
            <apex:outputText value="{!m1[dirKey]}"/>
            <apex:facet name="header" > <div align="center"> Exercice </div> </apex:facet>
        </apex:column>

    </apex:pageBlockTable>

And I get the following error even if the field I'm trying to access exist in the object custom fields and should exist in the map.

the only solution is to manually add:

FieldsList.add('Total des capitaux propres (A)');
                if(obj.Total_des_capitaux_propres_A__c==null)
                 {
                     m1.put('Total des capitaux propres (A)','');
                 }
                 else
                 {
                     m1.put('Total des capitaux propres (A)',String.valueOf(obj.Total_des_capitaux_propres_A__c));
                 }

Best Answer

Typically you should use the API Name as the map key because it is unique. Also if you want to ensure that you get an exact match, it is probably best to use field describes.

fieldsList.add(Opportunity.My_Custom_Field__c.getDescribe().getName());

Even a simple case mismatch or trailing whitespace could cause your manual additions to fail, and if those labels change then poof, your code breaks again.

In your VisualForce, you can still render the label using the API Name:

{!$ObjectType.Opportunity.fields[apiName].label}
Related Topic