Adding rows in visualforce page in PageBlocktable dynamically

apex-codesalesforcevisualforce

i am creating a dummy visualforce page whose code is

<apex:page controller="sampleCon">
    <apex:form>
    <apex:pageMessages id="message" />
    <apex:pageBlock>
    <apex:pageBlockTable value="{!wrap1}" var="item" id="hello">
    <apex:column headerValue="String" value="{! item.x}"></apex:column>
    <apex:column headerValue="Action"><apex:commandButton value="{!if(item.i == size-1,'Add','Delete')}" onclick="AddOrDelete({! item.i});" rerender="message"></apex:commandButton></apex:column>
    </apex:pageBlockTable>
    </apex:pageBlock>
    <apex:actionRegion >
     <apex:actionFunction name="AddOrDelete" action="{!addElement}" reRender="message,hello">
     <apex:param value="" name="fieldName" />
  </apex:actionFunction>
     </apex:actionRegion>
    </apex:form>
</apex:page>

and the controller code is

public class sampleCon {
public List<Wrapper> wrap1{get;set;}
public Integer size{get;set;}

public sampleCon(){
wrap1=new List<Wrapper>();
wrap1.add(new wrapper(0));
 size=wrap1.size();

}

public PageReference addElement(){
size=wrap1.size();


System.debug('Hello ji'+Apexpages.currentPage().getParameters().get('fieldName')+'size is'+size);
Integer i=Integer.valueOf(ApexPages.currentPage().getParameters().get('fieldName'));

if(i == size-1)
{
wrap1.add(new wrapper(size));

size++;
}

return null;

}


    public class wrapper{
    public integer i{get;set;}
    public String x{get;set;}
    public wrapper(Integer p){
i=p;
    }}
    }

what i am trying is the last row button label should be Add and other button label should be Delete when i press add button a new row is added and the label should be changed acordingly for this i am adding row but it is not working as expected

initial page screenshot is
enter image description here
when i press add button screen look like this.
enter image description here
when i again press the Add button screen is looking like first screenshot.i was expecting that one more row will be added when i click add button in above screenshot.can any one please tell why only one row is showing when i click add button in second screen shot and how to correct it that when i again click on add button on above screen one more row will be added instead of showing initial screen.

Best Answer

Related Topic