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
Aditya Rayavarapu 5Aditya Rayavarapu 5 

Insert Contact with Self Lookup

Hello,
I have a self lookup relationship in my Contact object, called 'Primary Sub'.

I want a VF page where you can enter two contacts. The second contact would have to be a child of the first contact.
To simplify my page, this is what the code looks like:

<apex:page controller="CustomController">
<apex:form >
 
            <apex:inputField value="{!c.lastname}" />
           
            <apex:inputField value="{!c.lastname}" />
            <apex:inputField value="{!c.Primary_Sub__c}" />
            
            <apex:commandButton action="{!save}" value="Save"/>
            </apex:form>
</apex:page>


And the controller:

public class CustomController {

public Contact c{get; set;}
Public String accId{get;set;}
Public String acc3{get;set;}

 public CustomController(){
        accId = ApexPages.currentPage().getParameters().get('LastName'); 
           if(accId != null)        
            {
                this.c= [   SELECT  LastName
                              FROM    Contact
                              WHERE   LastName = : accId ];  
            }
            else
            {this.c= new Contact();}  
            
            acc3 = ApexPages.currentPage().getParameters().get('Primary_Sub__c'); 
           if(acc3 != null)        
            {
                this.c= [   SELECT  Primary_Sub__c
                              FROM    Contact
                              WHERE   Primary_Sub__c = : acc3 ];  
            }
            else
            {this.c= new Contact();}          
    
}

public pagereference  save(){
    
        insert this.c;
         c.Primary_sub__c=accId;
         insert this.c;
        
        PageReference reRend = new PageReference('/apex/Thankyou'); 
        reRend.setRedirect(true);
                return reRend;
             
}
}


I'm trying to workout the logic where the lookup field for the second field can be populated with the first contact, and then Inserted.
Any suggestions?
Thanks
Adi
ShashankShashank (Salesforce Developers) 
Instead of 

c.Primary_sub__c=accId;

You should query for the Id of that contact and populate the ID in the Primary_suc__c field and then insert the second contact
Aditya Rayavarapu 5Aditya Rayavarapu 5
Hi Shashank,
the problem is that the primary contact doesn't exist yet. I want to create them both at the same time.
ShashankShashank (Salesforce Developers) 
I'm afraid I do not have a solution for that, since we would definitely need the ID of the record to populate a lookup field. However, once you insert one record, you can query for it and get the record ID and use it to populate the field.