Grid Table using PageBlock / DataTable / repeat in Visualforce Pages

Visualforce Aug 29, 2014

Grid Table is useful when user wants to,

  1. View All records in edit mode
  2. Able to Add New Record
  3. Save All Records with Single button

Okay! Then which one to use <apex:pageBlockTable> or <apex:dataTable> or <apex:repeat> Check here

Example Explained

Displaying as PageBlockTable

Visualforce Page

<apex:page standardController="Student__c" extensions="grid_all_editable_ext">
    <apex:form id="formId">
        <apex:pageBlock>
            <apex:pageBlockTable value="{!student_list}" var="st">
                <apex:column headerValue="Name">
                    <apex:inputField value="{!st.First_Name__c}" />
                </apex:column>
                <apex:column headerValue="Mobile">
                    <apex:inputField value="{!st.Mobile__c}" />
                </apex:column>
                <apex:column headerValue="Email">
                    <apex:inputField value="{!st.Email__c}" />
                </apex:column>
                <apex:column headerValue="Occupation">
                    <apex:inputField value="{!st.Occupation__c}" />
                </apex:column>
                <apex:column headerValue="DOJ">
                    <apex:inputField value="{!st.Date_of_Joining__c}" />
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller

public class grid_all_editable_ext {

    public List<student__c> student_list {get; set;}

    public grid_all_editable_ext(ApexPages.StandardController controller) {
        student_list = [SELECT Id, Name, OwnerId, First_Name__c, Last_Name__c, Mobile__c, 
        				Email__c, Date_of_Joining__c, Occupation__c 
        				FROM Student__c];
    }
}

Output

Okay cool! successfully displayed all field as Editable but now

How to Add new Record?

  • Add `` as follows under ``,
    	<apex:pageBlockButtons >
             <apex:commandButton value="Add New Student" action="{!addNew}"/>
        </apex:pageBlockButtons>
    
  • Add `addNew()` method in controler as follows,
    public void addNew(){
    	student_list.add(new Student__c());
    }
    
  • **Sample output**, screenshot after hitting "Add New Student" button ![](/content/images/2014/Aug/Add-new-row.png)

    How to Save All Records

  • Add after **addNew** `` under ``,
    <apex:commandButton value="Save Records" action="{!Save}"/>
    
  • Add `save()` method in controler as follows,
    public void save(){
    	upsert student_list;
    }
    

    That's it! please comment below if you need any help

  • Phanindra Mangipudi

    Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap