0

My code fails for multiselection of describe object iam getting following error.

System.NullPointerException: Attempt to de-reference a null object Error is in expression '{!showFields}' in component in page describ: Class.APU001_Describe.showFields: line 53, column 1

Class.APU001_Describe.showFields: line 53, column 1

Below is my code VF page code

<apex:page controller="APU001_Describe"   contentType="{!renderAsExcel}" sidebar="false">

<style>
  fieldset.scheduler-border {
    border: 1px groove #ddd !important;
    padding: 0 1.4em 1.4em 1.4em !important;
    margin: 0 0 1.5em 0 !important;
    -webkit-box-shadow:  0px 0px 0px 0px #000;
    box-shadow:  0px 0px 0px 0px #000;
    margin-left:8% !important;
    width:63%;
}

    legend.scheduler-border {
        font-size: 1.2em !important;
        font-weight: bold !important;
        text-align: left !important;
        width:auto;
        padding:0 10px;
        border-bottom:none;
    }
    .bodyDiv{
 height:400px;
}
.Btn-group{
  width:60% !important;
}
.frm{
  margin:15px;
}
.modal {
    outline:none;
}
</style>  
<apex:form id="Describe">


 <apex:pageBlock id="block2" >
<apex:pageblockbuttons location="top" >
<apex:commandButton value="Fetch Object Fields"  rerender="Describe" action="{!showFields}"/>

</apex:pageblockbuttons>
<apex:pageblocksection >

<apex:selectList value="{!selectedObject}" multiselect="True" size="3">


<apex:selectOptions value="{!objectNames}" />



</apex:selectList>

</apex:pageblocksection>


 <apex:pageBlockTable value="{!fields}" var="fls">  
    <style>
body
{
   background-color: blue; } 
 <apex:column value="{!fls.key}" headerValue="Field Name"/> 
 <apex:column value="{!fls.fieldAPIName }" headerValue="Field API Name"/>    
 <apex:column value="{!fls.val}" headerValue="Field Type"/> 
          </style>

</apex:pageBlockTable>


<apex:pageblocksection id="fieldList" rendered="{!not(isnull(selectedObject))}">




     <!--Apex:commandButton value="Export to Excel" action="{!SaveAsCSV}" /-->
    <Apex:commandButton value="Export to Excel" onclick="return window.open('/apex/Describ?core.apexpages.devmode.url=1)"/>


</apex:pageblocksection>
</apex:pageBlock>
</apex:form>
 </apex:page>

Below is my controller code

public class APU001_Describe
{
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
public List<Pair> lstfieldname{get;set;}
public List <Pair> fields {get{return lstfieldname;} set{lstfieldname =value;}}
public List <SelectOption> objectNames{public get; private set;}
public List<SelectOption> fieldNames {public get; private set;}   
public String selectedFields {get; set;}    
public String selectedObject {get; set;}
public string header{get;set;}
public string renderAsExcel{get;set;}


// Intialize objectNames and fields

public APU001_Describe() {
objectNames = initObjNames();
fields = new List<Pair>();

header ='lstfieldname,fields,objectName\r\n';
}
// Populate SelectOption list -

// find all sObjects available in the organization

private List<SelectOption> initObjNames() {
List<SelectOption> objNames = new List<SelectOption>();
 List<SelectOption> fieldNames = new List<SelectOption>();
List<String> entities = new List<String>(schemaMap.keySet());
entities.sort();
for(String name : entities)
objNames.add(new SelectOption(name,name));
return objNames;

}




 // public PageReference SaveAspdf() {      
        //renderAsdoc='pdf';
        //setup a default file name
       // string fileName = 'DataList '+date.today()+'.pdf';
       // Apexpages.currentPage().getHeaders().put('content-disposition', 'attachemnt; filename='+fileName);      
      //  return null;
   // }

// Find the fields for the selected object

public  void showFields() {
fields.clear();

Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();




for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
//system.debug('#######' + dfield );
Pair field = new Pair();
field.key = dfield.getLabel();
//system.debug('#######4444' + field.key);
field.val = dfield.getType () + ' : ' + dfield.getLabel ();
field.fieldAPIName = dfield.getname();

//field.formulafield =dfield.calculatedformula();
//field.Length = dfield.getLength();
lstfieldname.add(field);
//renderAsExcel='application/vnd.ms-excel#Data Report.csv';
}
    for(Schema.SObjectField sfield : fieldMap.Values()){
    schema.describefieldresult dfield = sfield.getDescribe();
    fieldNames.add(new SelectOption(dfield.getName(),dfield.getLabel()));
}
}

 public PageReference SaveAsCSV() {
        renderAsExcel='application/vnd.ms-excel#Data Report.xls';
   return null;
 }
public class Pair
{
public String key {get; set;}
public String val {get; set;}
public String fieldAPIName{get;set;}
//public String Length{get;set;}
 //public String formulafield{get;set}
}
}
  • It would be helpful if you could format this code with clear indentation and call out which line is line 53. – David Reed Dec 9 '19 at 15:40
0

Since it's a multi-select, but you're putting it in to a string, you'll end up trying to get values that don't exist in the field map. Instead, you'd want to use a list, and if there are any selected values, then use those.

Here's the minimum changes you'd need to make:

public String[] selectedObject {get; set;}

...

public  void showFields() {
    fields.clear(); 
    if(selectedObject != null) {
        for(String obj: selectedObject) {
            Map <String, Schema.SObjectField> fieldMap = schemaMap.get(obj).getDescribe().fields.getMap();
            for(Schema.SObjectField sfield : fieldMap.Values())
            {
                schema.describefieldresult dfield = sfield.getDescribe();
                //system.debug('#######' + dfield );
                Pair field = new Pair();
                field.key = dfield.getLabel();
                //system.debug('#######4444' + field.key);
                field.val = dfield.getType () + ' : ' + dfield.getLabel ();
                field.fieldAPIName = dfield.getname();

                //field.formulafield =dfield.calculatedformula();
                //field.Length = dfield.getLength();
                lstfieldname.add(field);
                //renderAsExcel='application/vnd.ms-excel#Data Report.csv';
            }
            for(Schema.SObjectField sfield : fieldMap.Values()){
                schema.describefieldresult dfield = sfield.getDescribe();
                fieldNames.add(new SelectOption(dfield.getName(),dfield.getLabel()));
            }
        }
    }
}

Feel free to rename the variables, etc, as necessary.


The fieldNames variable needs to be initialized. The initObjNames method initializes a local variable by the same name, but that's not the same variable as in the class.

public APU001_Describe() {
    objectNames = initObjNames();
    fields = new List<Pair>();
    fieldNames = new List<SelectOption>();
    header ='lstfieldname,fields,objectName\r\n';
}

Which you should probably clear() before starting anew in the showFields function:

public void showFields() {
    fieldNames.clear();
    // rest of code from above
  • After using public String[] selectedObject {get; set;} iam getting following error for my code Method does not exist or incorrect signature: void get(List<String>) from the type Map<String,Schema.SObjectType> – psalesforce1989 Dec 9 '19 at 19:18
  • @psalesforce1989 Notice I added a loop, and we're getting the individual objects from the selected objects (I use obj instead of selectedObject). – sfdcfox Dec 9 '19 at 19:26
  • i fixed that but the errror here is the same now its System.NullPointerException: Attempt to de-reference a null object Error is in expression '{!showFields}' in component <apex:commandButton> in page describ: Class.APU001_Describe.showFields: line 80, column 1 and line 80 is fieldNames.add(new SelectOption(dfield.getName(),dfield.getLabel())); – psalesforce1989 Dec 9 '19 at 19:28
  • @psalesforce1989 Ah, another small detail--` List<SelectOption> fieldNames = new List<SelectOption>();` should be fieldNames = new List<SelectOption>();, preferably in the constructor. I'll edit this in. – sfdcfox Dec 9 '19 at 19:37
  • Don't know while after selecting multi objects inspite of giving output it is erroring out with the errror attempt to de reference a null object error in expression as mentioned earlier – psalesforce1989 Dec 9 '19 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.