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
Esther Thomas 2Esther Thomas 2 

Associating an existing parent record with a new child record in visualforce

Hi All,
 I'm using a custom apex controller. I have some master/detail relationships between some custom objects (Client --> Booking)
I'm trying to create a new child record on the Booking object (dependent child object). 
How do I specify the reference to the parent object when creating this new Booking record. 
I have a soql query that returns the existing clients which are then displayed in a selectList. 
I want to be able to associate the selected record in that select list as the master record associated with this new booking record. 
I'm hoping I'm not confusing the crap out of everyone. 
Here is my schema:
User-added image

Also as this is a custom controller, do I have to assign the Last Modified Date, Created By field values explicitly I can create a new booking record? I'm assuming nothing comes for free here? I'm not even sure what I'm suppose to put in those for those either. My primary hiccup is how do I assign the Availability and Client fields? Does that have to equal the Client.Name from the client object and Availability.Name from Availability Object?
 
<apex:page standardController="Booking__c" extensions="testing10" docType="html-5.0">
    <apex:form >
    	<apex:pageBlock >
        	<apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                <apex:outputLabel >Booking Date</apex:outputLabel>
                <apex:inputfield value="{!Records.Start_Date_Time__c}">
                <apex:actionSupport action="{!UpdateSitter}" event="onchange" reRender="D1"/>   
           		</apex:inputfield>
	        </apex:pageBlockSectionItem>                 
                </apex:pageBlockSection>
            
            <apex:pageBlockSection columns="1" id="D1">
                 <apex:outputLabel rendered="{!FlagH}">Baby Sitters</apex:outputLabel>
                 <apex:selectList value="{!SelectedSitter}" size="1" rendered="{!FlagH}"> <!--var holding selected item-->
                 <apex:selectOptions value="{!RecordOption}" rendered="{!FlagH}"/> 
                  </apex:selectList>
              
                  <apex:outputLabel rendered="{!FlagH}">Clients</apex:outputLabel>
                  <apex:selectList value="{!SelectedClient}" size="1" rendered="{!FlagH}"> <!--var holding selected item-->
                  <apex:selectOptions value="{!ClientOption}" rendered="{!FlagH}"/> 
                  </apex:selectList>
                
                  <apex:outputLabel rendered="{!FlagH}">Number of Hours Needed</apex:outputLabel>
                  <apex:input type="number" id="hoursI" value="{!hours}" html-min="2" html-max="8" rendered="{!FlagH}"/      
                
              <apex:pageBlockTable value="{!Sdate}" var="sd" rendered="{!FlagH}">
                    <apex:column value="{!sd}"/>
                   <apex:column value="{!Record.End_Date_Time__c}"/>
             </apex:pageBlockTable>
                
              </apex:pageBlockSection>
              <apex:pageBlockButtons location="bottom">
	          <apex:commandButton action="{!save}" value="Save"/>
	          </apex:pageBlockButtons>
        
        </apex:pageBlock>
    </apex:form>
</apex:page>

public class testing10 {
   public Booking__c Records{get;set;}
    public Boolean FlagH{get;set;}
    public Datetime DTime {get;set;}
    public List<SelectOption> RecordOption{get;set;} //stores the babysitters names in the picklist
    public Date PickDate{get;set;}
    public String Sdate{get;set;}
    public String SelectedSitter{get;set;}
    public String SelectedClient{get;set;}
    public List<SelectOption> ClientOption{get;set;} 
    public Integer hours{get;set;} 
  
 
    public PageReference UpdateSitter(){
  
      RecordOption = new List<SelectOption>();  //list to hold my babysitters returned 
      ClientOption = new List<SelectOption>(); //list to hold clients
        
        try{
          Dtime = Records.Start_Date_Time__c; //retrive datetime input 
          PickDate= DTime.date(); //convert datetime to date type
          Sdate = String.valueOf(PickDate);
          SelectedClient ='';
            
          RecordOption.add(new SelectOption('', '----Noness----'));
          ClientOption.add(new SelectOption('', '----Select Client----'));
            
          List<Availability__c> tempval = new List<Availability__c>([SELECT Id, Name, BabySitter__r.name, BabySitter__r.First_Name__c from Availability__c WHERE Date_Available__c =: PickDate and Booked__c=FALSE]);
          List<Client__c> tempClient = new List<Client__c>([SELECT Id, Name, First_Name__c, Last_Name__c from Client__c]);
            FlagH=false; //hides rendered block until returned date has an associated value (babysitters)
            if(tempval.size() > 0){  //babysitters are found
                FlagH=true;
                for(Availability__c a : tempval){
                    RecordOption.add(new SelectOption(a.Id, a.BabySitter__r.First_Name__c));
                }
               
                if (tempClient.size() > 0){
                      for(Client__c c : tempClient){
                    	ClientOption.add(new SelectOption(c.Id, c.Name));
                	}
				}
                
                //calculate end date/time
                Records.End_Date_Time__c = Records.Start_Date_Time__c + (hours/24);
                
                //assign client to new booking??????
                Records.Client__c = SelectedClient;
                
                //assign Availability/sitter?????????
                Records.Availability__r.Name = SelectedSitter;
              
            }
           
       
        }catch(Exception e){
            
        }    
       
        return null;
    }
    
    public PageReference save(){
        insert Records;
        //need to save booking with selected babysitter, selected date
        //update availability to booked (boolean)
        //return to listview page (parent page)
        return null;
    }
    public testing10(ApexPages.StandardController controller){
        FlagH = false;
        SelectedClient ='';
        SelectedSitter = '';
        Records = (Booking__c)controller.getRecord();
        
        
    }
    public testing10(){}
}

 
Best Answer chosen by Esther Thomas 2
PrabhaPrabha
Found the issue,  actually two.

All of your logic is in the method - UpdateSitter.

You are calling it only in the rerendering of first selection. I would move my logic to save method or create an additional method.
"records" is the variable that needs user data. so moving it to Save method for the time being.

Second thing is "Records.Availability__r.Name = SelectedSitter;" you cannot do that in APEX. 

Here is the working code:
 
public class testing10 {
   public Booking__c Records{get;set;}
    public Boolean FlagH{get;set;}
    public Datetime DTime {get;set;}
    public List<SelectOption> RecordOption{get;set;} //stores the babysitters names in the picklist
    public Date PickDate{get;set;}
    public String Sdate{get;set;}
    public String SelectedSitter{get;set;}
    public String SelectedClient{get;set;}
    public List<SelectOption> ClientOption{get;set;} 
    public Integer hours{get;set;} 
  
 
    public PageReference UpdateSitter(){
  
      RecordOption = new List<SelectOption>();  //list to hold my babysitters returned 
      ClientOption = new List<SelectOption>(); //list to hold clients
        
        try{
          Dtime = Records.Start_Date_Time__c; //retrive datetime input 
          PickDate= DTime.date(); //convert datetime to date type
          Sdate = String.valueOf(PickDate);
           
          RecordOption.add(new SelectOption('', '----Noness----'));
          ClientOption.add(new SelectOption('', '----Select Client----'));
            
          List<Availability__c> tempval = new List<Availability__c>([SELECT Id, Name, BabySitter__r.name, BabySitter__r.First_Name__c from Availability__c WHERE Date_Available__c =: PickDate and Booked__c=FALSE]);
          List<Client__c> tempClient = new List<Client__c>([SELECT Id, Name, First_Name__c, Last_Name__c from Client__c]);
            FlagH=false; //hides rendered block until returned date has an associated value (babysitters)
            if(tempval.size() > 0){  //babysitters are found
                FlagH=true;
                for(Availability__c a : tempval){
                    RecordOption.add(new SelectOption(a.Id, a.BabySitter__r.First_Name__c));
                }
               
                if (tempClient.size() > 0){
                      for(Client__c c : tempClient){
                        ClientOption.add(new SelectOption(c.Id, c.Name));
                    }
                }
                
               // PrabhaN: commenting
                //assign Availability/sitter?????????
               // Records.Availability__r.Name = SelectedSitter;
              
            }
           
       
        }catch(Exception e){
            
        }    
       
        return null;
    }
    
    public PageReference save(){
    
    try{
                //calculate end date/time
                Records.End_Date_Time__c = Records.Start_Date_Time__c + (hours/24);
                
                //assign client to new booking??????
                Records.Client__c = SelectedClient;
                
        insert Records;
        //need to save booking with selected babysitter, selected date
        //update availability to booked (boolean)
        //return to listview page (parent page)
}catch(Exception e){ 

return null
} 
        return null;
    }
    public testing10(ApexPages.StandardController controller){
        FlagH = false;
        SelectedClient ='';
        SelectedSitter = '';
        Records = (Booking__c)controller.getRecord();
        
        
    }
    public testing10(){}
}


 

All Answers

PrabhaPrabha
The code looks fine to me for the first reading, let me create the schema and run this in my dev org. 
PrabhaPrabha
Found the issue,  actually two.

All of your logic is in the method - UpdateSitter.

You are calling it only in the rerendering of first selection. I would move my logic to save method or create an additional method.
"records" is the variable that needs user data. so moving it to Save method for the time being.

Second thing is "Records.Availability__r.Name = SelectedSitter;" you cannot do that in APEX. 

Here is the working code:
 
public class testing10 {
   public Booking__c Records{get;set;}
    public Boolean FlagH{get;set;}
    public Datetime DTime {get;set;}
    public List<SelectOption> RecordOption{get;set;} //stores the babysitters names in the picklist
    public Date PickDate{get;set;}
    public String Sdate{get;set;}
    public String SelectedSitter{get;set;}
    public String SelectedClient{get;set;}
    public List<SelectOption> ClientOption{get;set;} 
    public Integer hours{get;set;} 
  
 
    public PageReference UpdateSitter(){
  
      RecordOption = new List<SelectOption>();  //list to hold my babysitters returned 
      ClientOption = new List<SelectOption>(); //list to hold clients
        
        try{
          Dtime = Records.Start_Date_Time__c; //retrive datetime input 
          PickDate= DTime.date(); //convert datetime to date type
          Sdate = String.valueOf(PickDate);
           
          RecordOption.add(new SelectOption('', '----Noness----'));
          ClientOption.add(new SelectOption('', '----Select Client----'));
            
          List<Availability__c> tempval = new List<Availability__c>([SELECT Id, Name, BabySitter__r.name, BabySitter__r.First_Name__c from Availability__c WHERE Date_Available__c =: PickDate and Booked__c=FALSE]);
          List<Client__c> tempClient = new List<Client__c>([SELECT Id, Name, First_Name__c, Last_Name__c from Client__c]);
            FlagH=false; //hides rendered block until returned date has an associated value (babysitters)
            if(tempval.size() > 0){  //babysitters are found
                FlagH=true;
                for(Availability__c a : tempval){
                    RecordOption.add(new SelectOption(a.Id, a.BabySitter__r.First_Name__c));
                }
               
                if (tempClient.size() > 0){
                      for(Client__c c : tempClient){
                        ClientOption.add(new SelectOption(c.Id, c.Name));
                    }
                }
                
               // PrabhaN: commenting
                //assign Availability/sitter?????????
               // Records.Availability__r.Name = SelectedSitter;
              
            }
           
       
        }catch(Exception e){
            
        }    
       
        return null;
    }
    
    public PageReference save(){
    
    try{
                //calculate end date/time
                Records.End_Date_Time__c = Records.Start_Date_Time__c + (hours/24);
                
                //assign client to new booking??????
                Records.Client__c = SelectedClient;
                
        insert Records;
        //need to save booking with selected babysitter, selected date
        //update availability to booked (boolean)
        //return to listview page (parent page)
}catch(Exception e){ 

return null
} 
        return null;
    }
    public testing10(ApexPages.StandardController controller){
        FlagH = false;
        SelectedClient ='';
        SelectedSitter = '';
        Records = (Booking__c)controller.getRecord();
        
        
    }
    public testing10(){}
}


 
This was selected as the best answer
Esther Thomas 2Esther Thomas 2
Thank you so much. sorry for the messy code. Yah I cleaned it up and made updates based on your feedback and suggestions.