0

I want to display field names along with records of Project__c object on my VF page but I am unable to do that;
Visual Force Page code:

<apex:page controller="WorkOnFields">
  <apex:form >
  <apex:pageBlock title="Records Loader">
      <apex:pageblockbuttons location="top">
            <apex:commandButton value="Get Fields with Records" action="{!loadRecords}"/>
      </apex:pageblockbuttons>
      <apex:pageblocksection >
                <apex:outputLabel value="Field List for Project:"/><br/>
                <apex:selectList value="{!fieldName}" size="5" multiselect="true">
                        <apex:selectOptions value="{!fieldNames}"/>
                </apex:selectList>
      </apex:pageblocksection>
      <apex:pageBlockSection >
          <apex:pageBlockTable value="{!sobjList}" var="record">
                <apex:repeat value="{!fieldName}" var="sobjList">
                  <apex:column value="{!record[sobjList]}"/>
                </apex:repeat>
          </apex:pageBlockTable>            
      </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>  
</apex:page>

Apex code:

public class WorkOnFields{

    public List<SelectOption> fieldNames{get;set;}
    public String fieldName{get;set;}
    public List<String> fieldList { get;set; }
    public List<SObject> sobjList { get;set; }
    
         
    public WorkOnFields(){
        fieldNames = new List<SelectOption>();        
        Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Project__c').getDescribe().fields.getMap();
        fieldList = new List<String>(objectFields.keySet()); 
              
        For(String field : fieldList){
            fieldNames.add(new SelectOption(field,field));
        }
    }
    
    public PageReference loadRecords() {
        System.debug(fieldName);
        fieldName = fieldName.substring(fieldName.indexOf('[')+1, fieldName.indexOf(']'));
        String startQuery = 'SELECT '; 
        String endQuery = ' FROM Project__c';
        String Query = startQuery + fieldName + endQuery;
        sobjList = Database.query(Query);
        System.debug(sobjList);
        return null;
    }
}

While I am clicking on the button "Get Fields with Records" I am getting; Exception: Invalid field end_date__c, project_stage__c, total_hours__c for SObject Project__c, Kindly help me rectify this.

1 Answer 1

1

fieldName should be a List:

public String[] fieldName{get;set;}

Now, you can just write:

public void loadRecords() {
    String startQuery = 'SELECT '; 
    String endQuery = ' FROM Project__c';
    String Query = startQuery + String.join(fieldName,',') + endQuery;
    sobjList = Database.query(Query);
    System.debug(sobjList);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .