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
Shravya Rama 9Shravya Rama 9 

Prepopulating lookup field using constructor

Hello All,
I have a custom childobject(Reservation) and a  lookup parent object(User). I am trying to prepopulate the look up field with the current user attributes. My lookup field accepts the values in the form of "UserFirstName UserLastName". So I tried to invoke the default values through constructor like below.

VisualForce Page:
<apex:page standardController="Reservation__c" extensions="ReservationClass" >
    <apex:sectionHeader title="New Reservation" />
    <apex:form >
       <apex:pageBlock>
        <apex:pageBlockSection >
            <apex:inputField value="{!order.User__c}"/>
  </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>
Custom Controller
public class ReservationClass {
    public Reservation__c res{get; set;}
    public String FName = UserInfo.getFirstName()  ;
    public String Lname = UserInfo.getLastName();
    public string UserName = FName + ' ' + Lname ;

public ReservationClass (ApexPages.StandardController stdController) {
    res = (Reservation__c) stdController.getRecord();
    res.User__c =  userName ;
  }
}
The above code throws an error
"Invalid id: Shravya Rama
 An unexpected error has occurred. Your development organization has been notified."

 
Best Answer chosen by Shravya Rama 9
Samer AboobackerSamer Aboobacker
Hi Shravya Rama 9, 

You will have to assign the user id to the User__c field. Pls try assigning the userinfo.getUserId().

All Answers

Samer AboobackerSamer Aboobacker
Hi Shravya Rama 9, 

You will have to assign the user id to the User__c field. Pls try assigning the userinfo.getUserId().
This was selected as the best answer
Shravya Rama 9Shravya Rama 9
Hi Samer Aboobacker,
Thank you. It worked!
Nagendra ChinchinadaNagendra Chinchinada
Shravya,

Lookup fields accept Ids only, not names.So res.User__c should be populated with Id of current user.
 
public class ReservationClass {
	public Reservation__c res{get; set;}

public ReservationClass (ApexPages.StandardController stdController) {
res = (Reservation__c) stdController.getRecord();
res.User__c = UserInfo.getUserId();
}
}

Please let me know if it helps.