Tag Archives: Add Row

Dynamically Add Delete Rows In PageBlockTable Visualforce Page

Apex Class:

public class DemoController {
    
    Public List<Account> accList {get;set;}
    public Integer rowIndex {get;set;}
    
    public DemoController(){
        accList = new list<Account>();
        accList.add(new Account());
    }
    
    public void addRow(){
        accList.add(new Account());
    }
    
    public pagereference saveAccount(){
        Insert accList;
        return null;
    }
    
    public PageReference deleteRow(){
        rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
        accList.remove(rowIndex);
        return null;
    }
}

Visualforce Page:

<apex:page controller="DemoController">
    <apex:form id="fm">
        <apex:pageBlock id="pb">
            <apex:variable var="rowNumber" value="{!0}"/> 
            <apex:pageBlockTable value="{!accList}" var="ac">
                <apex:column headerValue="Account Name">
                    <apex:inputField value="{!ac.Name}"/>
                </apex:column>
                <apex:column headerValue="Account Number">
                    <apex:inputField value="{!ac.AccountNumber}"/>
                </apex:column>
                <apex:column headerValue="Account Type">
                    <apex:inputField value="{!ac.Type}"/>
                </apex:column>
                <apex:column headerValue="Industry">
                    <apex:inputField value="{!ac.Industry}"/>
                </apex:column>
                <apex:column headerValue="Action" >
                    <apex:commandButton value="Delete" action="{!deleteRow}" reRender="pb">
                        <apex:param name="rowIndex" value="{!rowNumber}"/>
                    </apex:commandButton>
                    <apex:variable var="rowNumber" value="{!rowNumber}"/>
                </apex:column>
            </apex:pageBlockTable>
            <apex:pageBlockButtons >
                <apex:commandButton value="Add Row" action="{!addRow}"/>
                <apex:commandButton value="Save Accounts" action="{!saveAccount}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output: