Tuesday 24 June 2014

How to pass lookup field id to controller?

Lets take an example. Suppose we want pass Accountid(look up field from contact to account) from visual force page to controller. If we choose one account from look up then automatically account industry will be populated.

Here is the page:-

<apex:page controller="passingLookupIdController">
  <script>
    function doSomething(test) {
      
        alert('hi-->'+test);
        PassingParameter1(test);
        // lkfield.value now has the selected ID value
    }
    </script>
 <apex:form >
  <apex:actionFunction name="PassingParameter1" action="{!PassingParameter}" reRender="field1">
  <apex:param value="" name="recordId"/>
  </apex:actionFunction>

   <apex:pageBlock >
          <apex:pageBlockSection id="someArea">

               <apex:inputField value="{!con.AccountId}" id="field">
                  <apex:actionSupport event="onchange" reRender="field"oncomplete="doSomething('{!con.AccountId}');"/>
              </apex:inputField>
               <apex:inputField value="{!account.Industry}" id="field1" />
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>


Here is controller:-

public with sharing class passingLookupIdController {
    public Contact con{get;set;}
     public Account account{get;set;}
    public passingLookupIdController (){
        con =  new Contact();       
    }
    public PageReference PassingParameter(){
        Id recordId = ApexPages.currentPage().getParameters().get('recordId');
        System.debug('Print--->'+recordId );
        account = [SELECT ID,Industry FROM Account WHERE id=:recordId ]; 
        return null; 
    }
}

No comments: