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
Vandana RattanVandana Rattan 

Rerender inputField using VisualForce actionSupport

I have a requirement to default the Company field on Lead creation page to First Name +" "+ Last Name as soon as user enters the Last Name. I am trying to use VisualForce actionSupport for the same. But rerender does not seem to work for me. I am attaching my code below. Any help would be much appreciated.

Visualforce Page:-

 
<apex:page standardController="Lead" extensions="leadControllerExtension">
    <apex:sectionHeader title="{!$ObjectType.Lead.label} Edit" subtitle="{!IF(ISNULL(Lead.name), 'New Lead', Lead.name)}"/>
    <apex:form >
        <apex:pageBlock mode="edit" title="{!$ObjectType.Lead.label} Edit">
            <apex:pageblockbuttons >
                <apex:commandbutton value="Save" action="{!Save}"/>
                <apex:commandbutton value="Cancel" action="{!Cancel}"/>
            </apex:pageblockbuttons>
           
             <apex:pageblocksection id="LeadInformationPBS" title="Lead Information">
             <!-- Make Owner field editable -->
             <apex:inputfield value="{!Lead.OwnerId}"></apex:inputfield>
             <apex:inputfield value="{!Lead.Phone}"></apex:inputfield>
 
             <!-- Since we need to group two input fields together we need a pageBlockSectionItem with an Output panel.  We also needed to create a label so we know what field we are entering in -->
             <apex:pageblocksectionitem >
             <apex:outputlabel value="{!$ObjectType.Lead.Fields.FirstName.label}"></apex:outputlabel>
             <apex:outputpanel >
             <apex:inputfield value="{!Lead.Salutation}"></apex:inputfield>
             <apex:inputfield value="{!Lead.FirstName}"></apex:inputfield>
             </apex:outputpanel>
             </apex:pageblocksectionitem>
             <apex:inputfield value="{!Lead.MobilePhone}"></apex:inputfield>
            
          
             <apex:inputfield value="{!Lead.LastName}">
             <apex:actionSupport event="onchange" reRender="CompanyDef" action="{!getCompany}"/>
             </apex:inputfield>
           
             <apex:inputfield value="{!Lead.Fax}"></apex:inputfield>
            
            
             <apex:inputField value="{!Lead.Company}" id="CompanyDef">
            
            
            
             </apex:inputField>
           
             <apex:inputfield value="{!Lead.Email}" required="true"></apex:inputfield>
            
             <apex:inputfield value="{!Lead.Title}"></apex:inputfield>
             <apex:inputfield value="{!Lead.Website}"></apex:inputfield>
            
             <apex:inputfield value="{!Lead.Leadsource}"></apex:inputfield>
             <apex:inputfield value="{!Lead.Status}"></apex:inputfield>
            
             <!-- <apex:inputField value="{!Lead.Campaign}" />
             Campaign field is not able to be used unless you write your own custom class/method to create a campaign member
             Post explaining this issue: http://boards.developerforce.com/t5/Apex-Code-Development/Cannot-Access-to-Campaign-Field-from-Lead-Object/td-p/161715
             -->
             <apex:inputfield value="{!Lead.Rating}"></apex:inputfield>
            
             <apex:inputfield value="{!Lead.Industry}"></apex:inputfield>
             <apex:inputfield value="{!Lead.NumberOfEmployees}"></apex:inputfield>
            </apex:pageblocksection>
          
       
        </apex:pageBlock>
    </apex:form>

</apex:page>

Controller:-

public class leadControllerExtension {

    transient public Lead lead {get; set;}
    transient public String Company {get; set;}
   
    // The extension constructor initializes the private member
    // variable acct by using the getRecord method from the standard
    // controller.
    public leadControllerExtension(ApexPages.StandardController stdController) {
        this.lead = (Lead)stdController.getRecord();
    }

    public String getCompany() {
    
     Company = lead.FirstName + ' ' + lead.LastName;
    
     Company='Hello Wprld';
       return (Company);
    }
}
 

Best Answer chosen by Vandana Rattan
bob_buzzardbob_buzzard

Sure - it should be pretty close to the following:

This example uses JQuery, so you'll need to make sure to include the Jquery library;
 

<apex:includescript value="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />


Change the input field to use an onchange handler and make sure that both the first and lastname have ids:

<apex:inputfield value="{!Lead.FirstName}" id='fname'></apex:inputfield>
<apex:inputfield value="{!Lead.LastName}" id='lname' onchange='nameChange();' />
then add a JavaScript method that concatenates the two fields and populates the company:
function nameChange()
{
   var full=$('[id$=fname]').val() + ' ' +    $('[id$=lname]').val();
   $('[id$=companyDef]').val(full);
}
This mechanism is a lot faster as its all done client side.  The downside is that you can't write a unit test to confirm the behaviour.

All Answers

bob_buzzardbob_buzzard

There's a few issues here - getCompany isn't an action method, its a getter for a string property, so you can't really call that from the action support in the way that you are trying to.

Also, your getter is just setting a local property in the class and returning it - that is disconnected from the lead on the page.  

In theory, you can update the company field as follows:

Page
 

<apex:inputfield value="{!Lead.LastName}">
    <apex:actionSupport event="onchange" reRender="CompanyDef" action="{!defineCompany}"/>
</apex:inputfield>
Controller:

public void defineCompany()
{
    lead.Company=lead.FirstName + ' ' + lead.LastName;
}

I have, however, found that the lead in an extension controller doesn't seem to be referring directly to the lead in the standard controller, so there may be problems with this.  Given that you are simply responding to a change to a field, I'd also consider doing this in JavaScript and avoiding the round trip to the server.


 

Vandana RattanVandana Rattan
Hi Bob,

Thanks for your reply. The thing you suggested was what I tried initially. It does seem to rerender the Company field (the field turns Red when I tab out of the Last Name) but the First Name + " " + Last Name isn't getting populated. I have tried using the onblur event too. But it's giving same result.

Can you please suggest something. My requirement is to auto populate Company with First Name + " " + Last Name. 

Also, can you please elaborate a bit on using Javascript instead of Controller.

Thanks in Advance
bob_buzzardbob_buzzard

Sure - it should be pretty close to the following:

This example uses JQuery, so you'll need to make sure to include the Jquery library;
 

<apex:includescript value="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />


Change the input field to use an onchange handler and make sure that both the first and lastname have ids:

<apex:inputfield value="{!Lead.FirstName}" id='fname'></apex:inputfield>
<apex:inputfield value="{!Lead.LastName}" id='lname' onchange='nameChange();' />
then add a JavaScript method that concatenates the two fields and populates the company:
function nameChange()
{
   var full=$('[id$=fname]').val() + ' ' +    $('[id$=lname]').val();
   $('[id$=companyDef]').val(full);
}
This mechanism is a lot faster as its all done client side.  The downside is that you can't write a unit test to confirm the behaviour.
This was selected as the best answer
Vandana RattanVandana Rattan
Thanks a tonn Bob!!
Gabe Rothman 8Gabe Rothman 8
Hi Bob,
Your solution here is great, I found it very helpful. I have however run into a problem I'm hoping you can help me to resolve.  I have a visualforce page that we use for product selection on our opportunities. I've updated it recently with a couple of Jquery functions (based on your response herein) that allow users to edit the sales price and auto-calculate the discount and vice versa. It works great if there is only one product added, but once I add more than a single product the calculations go wonky -- I assume because the code does not know which row to update.
One Product
User-added image
Two Products
User-added image


How can I ensure that my jquery is only updating field values in the row I'm editing?

Relevant Code
<script type='text/javascript'>

        function calculateDiscount(){
            var discount= 100*($('[id$=dp]').text() - $('[id$=sp]').val())/$('[id$=dp]').text();
            var discountRounded = discount.toFixed(1);
            $('[id$=disc]').val(discountRounded);
        }        

        function calculateSalesPrice(){
            var salesPrice= $('[id$=dp]').text() - ($('[id$=dp]').text() * $('[id$=disc]').val())/100;
            var salesPriceRounded = salesPrice.toFixed(2);
            $('[id$=sp]').val(salesPriceRounded);
        }             
</script>


<apex:form >
        <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">

            <apex:pageblockTable value="{!shoppingCart}" var="s">

                <apex:column >
                    <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">

                        <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                    </apex:commandLink>
                </apex:column>

                <!--********** Product Name **********-->
                <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>

                <!--********** Product SKU **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.SKU__c.Label}" value="{!s.PriceBookEntry.Product2.SKU__c}"/> 

                <!--********** Annual Product Term **********-->
                <apex:column headerValue="Annual Term" id="pt" rendered="false" value="{!s.PriceBookEntry.Product2.Product_Term_Years__c}"/>                         

                <!--********** Quantity **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                    <apex:inputField value="{!s.Quantity}" id="quant" style="width:70px" required="true">
                        <apex:actionSupport event="onchange" reRender="tot"/>
                    </apex:inputField>
                </apex:column>

                <!--********** Service Term in Months **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Service_Term_in_Months__c.Label}">
                    <apex:inputField value="{!s.Service_Term_in_Months__c}" id="svc" style="width:70px" required="true">
                        <apex:actionSupport event="onchange" reRender="tot"/>
                    </apex:inputField>
                </apex:column>                                        

                <!--********** Discount (Manual) **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Discount_off_list_manual__c.Label}">
                    <apex:inputField value="{!s.Discount_off_list_manual__c}" id="disc" style="width:70px" required="True" onkeyup="calculateSalesPrice();">
                        <apex:actionSupport event="onkeyup" reRender="spproxy"/> 

                         <!--<apex:actionSupport event="onkeyup" action="{!calculateSalesPrice}"/>-->
                    </apex:inputField>                                            
                </apex:column>                    

                <!--********** Sales Price **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                    <apex:inputField value="{!s.UnitPrice}" id="sp" style="width:70px" required="true" onkeyup="calculateDiscount();">
                        <apex:actionSupport event="onchange" reRender="tot"/>
                    </apex:inputField>                                          
                </apex:column>

                <!--********** Disti Transfer Price (Standard) Hidden **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Disti_Transfer_Price__c.Label}" rendered="True">
                    <apex:outputText id="dp" value="{!s.PriceBookEntry.Disti_Transfer_Price__c}"/>
                </apex:column>

                <!--********** List Price (Standard) Hidden **********-->
                <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.ListPrice.Label}" id="lp" value="{!s.PriceBookEntry.UnitPrice}" rendered="True"/>

                <!--********** Total Price (display only field) **********-->
                <apex:column headerValue="Total Price">
                    <apex:outputText id="tot" value="${0, number, ###,###,###,##0.00}">
                        <apex:param value="{!IF(s.PriceBookEntry.Product2.Product_Term_Years__c != null,(s.Quantity * s.Service_Term_in_Months__c * s.UnitPrice)/(s.PriceBookEntry.Product2.Product_Term_Years__c*12),(s.Quantity * s.UnitPrice)) }"/>
                    </apex:outputText> 
                </apex:column>                                   

            </apex:pageblockTable>


            <apex:pageBlockButtons >
                <apex:commandButton action="{!onSave}" value="Save"/>
                <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
            </apex:pageBlockButtons>

        </apex:pageBlock>