In this scenario we have shown the dynamic Add rows & Remove rows functionality in vf.
By using this we have shown multiple records insert.
Apex Controller
public class dynamicRowsAdd {
public List<InnerClassAccountList> accList {get;set;}
public Integer rowToRemove {get;set;}
public dynamicRowsAdd(){
accList = new List<InnerClassAccountList>();
addNewRowToAccList();
}
public PageReference SaveMultipleAccounts(){
system.debug('==accList==>'+accList.size());
List<Account> insertedAccountRecords = new List<Account>();
if(accList !=null && !accList.isEmpty()){
for(InnerClassAccountList eachRecord : accList ){
Account accTemp = eachRecord.record;
insertedAccountRecords.add(accTemp);
}
system.debug('==insertedAccountRecords==>'+insertedAccountRecords.size());
insert insertedAccountRecords;
}
pagereference pg = new pagereference('/apex/dynamicRowsAdd');
pg.setredirect(true);
return pg;
}
public void removeRowFromAccList(){
accList.remove(rowToRemove);
}
public void addNewRowToAccList(){
InnerClassAccountList newRecord = new InnerClassAccountList();
Account newAccountRecord = new Account();
newRecord.record = newAccountRecord;
newRecord.index = accList.size();
accList.add(newRecord);
}
public class InnerClassAccountList{
public Integer index {get;set;}
public Account record {get;set;}
}
}
Visualforce Page
<apex:page controller="dynamicRowsAdd">
<apex:form id="Form">
<apex:pageblock id="PB" title="Creating Multiple Accounts">
<apex:pageblockButtons location="top" >
<apex:commandButton value="Save" action="{!SaveMultipleAccounts}" />
</apex:pageblockButtons >
<apex:outputPanel id="accountHead">
<apex:variable value="{!0}" var="rowNum"/>
<apex:pageBlockSection columns="1" title="Add Multiple Accounts Here" id="Pbs" collapsible="False">
<apex:pageBlockTable value="{!accList}" var="everyRecord">
<apex:column headerValue="Action">
<apex:commandLink value="Remove" style="color:red" action="{!removeRowFromAccList}" rendered="{!rowNum > 0}" rerender="accountHead" immediate="true" >
<apex:param value="{!rowNum}" name="rowToRemove" assignTo="{!rowToRemove}"/>
</apex:commandLink>
<apex:variable var="rowNum" value="{!rowNum + 1}"/>
</apex:column>
<apex:column headerValue="Account Name">
<apex:inputField value="{!everyRecord.record.Name}" />
</apex:column>
<apex:column headerValue="Account Number">
<apex:inputField value="{!everyRecord.record.AccountNumber}" />
</apex:column>
<apex:column headerValue="Industry">
<apex:inputfield value="{!everyRecord.record.Industry}" />
</apex:column>
<apex:column headerValue="Rating">
<apex:inputfield value="{!everyRecord.record.Rating}" />
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
<apex:commandButton value="Add More Rows" action="{!addNewRowToAccList}" rerender="accountHead" Status="status" immediate="true" />
</apex:outputPanel>
</apex:pageblock>
</apex:form>
</apex:page>
Output