How do I dynamically add input fields on a Visualforce page?

Currently I have created a text box that allows the user to enter a comma delimited list of values that will be parsed and create new records en masse.

I am now trying to re-create this functionality, but by allowing input via multiple input boxes. Specifically, I would like to allow the user to dynamically add/remove new input boxes to the Visualforce layout and submit them all when a button is clicked.

This way, the controller can then create a new record for each input box that has a value in it rather than having to parse a comma-delimited list that may be incorrect.

Is this possible?


The most basic example will be something like the following (haven’t tested it, just typed on the fly):


public with sharing class YourClass
    public class CustomAccount
        public String accountName {get; set;}

    public List <CustomAccount> customAccounts {get; set;}

    public YourClass()
        customAccounts = new List <CustomAccount> ();

    public void addNewRecord()
        CustomAccount customAccount = new CustomAccount();

    public void insertAccounts()
        List <Account> accounts = new List <Account> ();

        for (CustomAccount customAccount : customAccounts)
            Account account = new Account();
            account.Name = customAccount.accountName;

        insert accounts;


<apex:page controller="YourClass">
    <apex:form id="form">
        <apex:repeat var="customAccount" value="{!customAccounts}">
            <apex:inputText value="{!customAccount.accountName}" />
        <apex:commandButton action="{!addNewRecord}" value="Add New" rerender="form" />
        <apex:commandButton action="{!insertAccounts}" value="Insert All" rerender="form" />

It should get you started, at least to get the idea, then you can modify it as you need to.

Source : Link , Question Author : toolshed , Answer Author : Boris Bachovski

Leave a Comment