function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Plural BPlural B 

How to add child records in visual force page at different child nodes?

We Have to built a tree Structure with Account as parent and Associated Contact record as child records.
We have Account1  with Contact 1.1 and Contact1.2  ;Account2 with Contact 2.1 and Contact2.2
When ever we try to add child records to Account2...... Contact Records are adding to Account1 instead of Account2
VF Page Code:
=============

<apex:page standardController="account" extensions="contactRelatedListwithAddrowsClass" id="pg">   
    <apex:form id="frm">
        <apex:pageBlock id="pb1" >
            <apex:variable value="{!0}" var="dateIndex"/>
            <apex:pageBlockTable value="{!contactlist}" var="c" id="dateTable">
                <apex:column style="color: #000;font-size: 11px;font-family:verdana;font-weight: bold;">
                    <apex:facet name="header">
                        <span style="color: #000;font-size: 11px;font-family:verdana;font-weight: bold;">
                            accounts
                        </span>    
                    </apex:facet>
                    <span id="date-sign-{!dateIndex}" class="sign-class" onclick="toggleDateTable('{!dateIndex}');">+</span>
                    <span style="color: #000;font-size: 11px;font-family:verdana;">
                        {!c.con.lastname}
                        
                    </span>
                    <apex:variable value="{!0}" var="stageIndex"/>
                    <apex:pageBlockTable value="{!c.con1}" var="oppRecord" id="stageTable" style="display:none;margin-top:10px;margin-left:20px;width:98%;">
                        
                        <span id="stage-sign-{!dateIndex}-{!stageIndex}" class="sign-class" onclick="toggleStagesTable('{!dateIndex}','{!stageIndex}');">+</span>
                        <span style="color: #000;font-size: 11px;font-family:verdana;font-weight: bold;">
                            {!oppRecord.lastname}
                        </span>
                        
                        <apex:column headerValue="Action" style="width: 85px;">
                            <apex:inputCheckbox />
                        </apex:column>
                        <apex:column headerValue="Name" >
                            <apex:inputField value="{!oppRecord.lastname}"/>
                        </apex:column>
                        <apex:column headerValue="Email" style="width: 200px;">
                            <apex:inputField value="{!oppRecord.Email}"/>
                        </apex:column>
                        <apex:column headerValue="Phone" style="width: 200px;">
                            <apex:inputField value="{!oppRecord.Phone}"/>
                        </apex:column>
                        <apex:column headerValue="Title" style="width: 200px;">
                            <apex:inputField value="{!oppRecord.title}"/>
                        </apex:column>
                        <apex:column >
                            <apex:commandLink value="Add" action="{!addrec}" immediate="true"> 
                                <!-- <a href="javascript:;" data-id="1" class="addelement">Add</a>
								<a href="javascript:;" data-id="1" class="removeelement">Del</a>-->
                                <apex:param name="pId" value="{!stageIndex}" assignTo="{!stageindex}"/>
                            </apex:commandLink> 
                            <apex:variable var="stageIndex" value="{!stageIndex + 1}"/>
                            {!stageIndex}
                        </apex:column>                                                
                    </apex:pageBlockTable>
                    <apex:variable value="{!dateIndex+1}" var="dateIndex"/>
                </apex:column>    
            </apex:pageBlockTable>    
        </apex:pageBlock>    
    </apex:form>
    
    <!-- Script Part -->
    <script src="//code.jquery.com/jquery-1.10.2.min.js"/>
    <script>
        $(document).ready(function(){
        // $(esc('pg:frm:pb1:dateTable:tb')+" > tr").attr("onmouseover","");
        // $("[id$='stageTable:tb'] > tr").attr("onmouseover","");
        // $(esc('pg:frm:pb1:dateTable:tb')+" > tr > td").hover(function(){$(this).css("background-color","ghostwhite");}, function(){$(this).css("background-color","white");});
        $("[id$='stageTable:tb'] > tr > td").hover(function(){$(this).css("background-color","greenyellow");}, function(){$(this).css("background-color","white");});
        $("[id$='stageTable'] > thead .headerRow").css("background-color","deepskyblue");
        
        
        $(document).on('click','.addelement',function(){
            $("#pg:frm:pb1:dateTable:0:stageTable:tb tr").clone().appendTo("#pg:frm:pb1:dateTable:0:stageTable:tb");
        });
    });
    
    function toggleDateTable(index){
        var signtext = $("#date-sign-"+index).text();
        var tableId = 'pg:frm:pb1:dateTable:'+index+':stageTable';
        if(signtext == '+'){
            $("#date-sign-"+index).text('-').css("padding", " 0px 7px");
            $(esc(tableId)).show();
        }
        else{
            $("#date-sign-"+index).text('+').css("padding", " 0px 5px");
            $(esc(tableId)).hide();
        }
    }
    
    /*  function toggleStagesTable(rootindex, childindex){
            var signtext = $("#stage-sign-"+rootindex+"-"+childindex).text(); //address-sign-index-addIndex
            var tableId = 'pg:frm:pb1:dateTable:'+rootindex+':stageTable:'+childindex+':opportunityTable';
            if(signtext == '+'){
                $("#stage-sign-"+rootindex+"-"+childindex).text('-').css("padding", " 0px 7px");
                $(esc(tableId)).show();
            }
            else{
                $("#stage-sign-"+rootindex+"-"+childindex).text('+').css("padding", " 0px 5px");
                $(esc(tableId)).hide();
            }
        }*/
    
    function esc(myid) {
        return '#' + myid.replace(/(:|\.)/g,'\\\$1');
    } 
    
    </script>
    <style>
        .sign-class{
        font-size: 12px;
        font-weight: 700;
        padding: 0px 5px;
        margin-right: 10px;
        border: 1px solid black;
        background: black;
        color: whitesmoke;
        margin-bottom:10px;
        cursor:pointer;
        }
        .pbBody table.list tr.dataRow td {
        font-family: verdana;
        font-weight: normal;
        }
    </style>
</apex:page>

==========================
Apex Class
======================

public class contactRelatedListwithAddrowsClass {
    public list<contact> ListContact{ get; set; }
    public list<contact> contacts{get; set;}
    public List<SubContact> contactList{get; set;}   
    public id accid{get; set;}
    public account acc{get; set;}
    public boolean displayrecords{get;set;}
    Public boolean nonerecords{get;set;}
    public list<account>acclist{get;set;}  
    public integer stageindex{get;set;}
    public id addindex{get;set;}
    
    public contactRelatedListwithAddrowsClass(ApexPages.StandardController ctrl){ 
        acclist=[select id,name,(select id,lastname, accountId from contacts),(select id, subject, accountId from cases) from account];
        acc=(account)ctrl.getRecord();// to get current record id of account.
        acclist.add(acc);
        //system.debug('acc records=='+acc);        
        contacts=[select id, lastname, email, phone, accountId, title, account.name from contact where accountId=:acc.Id];
        // based on account id will get contacts of account through this.
        accid=acc.id;        
        //system.debug('List of Contacts=='+ListContact);
        contactList=getcontacts();
        //system.debug('List of MainContacts=='+contactList);                    
    }       
    
    public PageReference addRec(){
     integer value=integer.valueof(apexpages.currentPage().getParameters().get('pId'));
       system.debug('value=='+value);
        contact c = new contact();       
        c.accountId=accId;
        if(contactList==null) {
            contactList = new List<SubContact>();
        }
        contactlist[value].con1.add(c);        
        return null;
    }
    
    
    public List<SubContact> getContacts() {
        if(contactList == null) {
            contactList = new List<SubContact>();
            for(Contact c: [select Id, LastName, Email, Phone, Title, accountId, account.name from Contact where accountId=:acc.Id ]) {
                // As each contact is processed we create a new SubContact object and add it to the contactList
                contactList.add(new SubContact(c));                
            }
        }
        return contactList;
    }
    
    public PageReference deletedRecords() {        
        //We create a new list of Contacts that we be populated only with Contacts if they are selected
        list<contact> selectedContacts = new List<Contact>();        
        //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
        for(SubContact Con1: getcontacts()) {
            if(Con1.selected == true && con1.con.id!=null) {
                selectedContacts.add(Con1.con);                
            }            
        }  
        delete SelectedContacts;        
        contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        getContacts();        
        return null;
    }
    public PageReference saveContacts() {        
        //We create a new list of Contacts that we be populated only with Contacts if they are selected
        list<contact> selectedContacts = new List<Contact>();
        
        //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
        for(SubContact Con1: getContacts()) {
            if(Con1.selected == true) {
                selectedContacts.add(Con1.con);
                
                con1.selected=false;
            }            
        }
        upsert SelectedContacts;
        contactList=null;
        getcontacts();
        //PageReference pageRef = ApexPages.currentPage();
        return null;
    }
    
    
    
    public class SubContact {
        public Contact con {get; set;}
        public list<contact>con1 {get;set;}
        public Boolean selected {get; set;}
        public integer rowId{get;set;}
        public account a{get;set;}
        
        //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
        public SubContact(Contact c) {
            con = c;
            con1=new list<contact>();
            con1.add(c);
            selected = false;                        
        }
    }    
}