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
Rick MacGuiganRick MacGuigan 

Keep focus on field after Save

I'm using a visual force page with an extended controller. When I click on the 'Save Only' button the page reloads to the top. How can I keep the focus on the field that a user was on prior to saving ? I am using the save action on the standard controller, not the extended controller. 
 
<apex:page id="page" standardController="Comm_Auto_Audit_Sample_Policy__c"  extensions="AuditCommAutoPolicySampleController"  > 
.....
<apex:commandButton styleClass="myClass" value="Save Only" action="{!Save}"/> 
<apex:commandButton styleClass="myClass" value="Save and Return to Template" action="{!saveAndReturn}"/>

 
Neetu_BansalNeetu_Bansal
Hi Rick,

You can reRender the section, although it would not refresh the page but yes you can lost the focus on the field that a user was prior to saving. I am curious to know why you want to focus on that field. Use reRender like this:
<apex:commandButton styleClass="myClass" value="Save Only" action="{!Save}" reRender="page" />
Let me know, if you need any other help.

Thanks,
Neetu
Rick MacGuiganRick MacGuigan
Neetu - thanks for the response. The VF page is long with several fields. I place the command button at the top and bottom of 5 seperate sections. If a user is editing say the thrid section they shouldbe able to save what data they've entered and move down to the next field or section. However, when they click Save the entire page is reloaded and scrolls to to top. My question is about staying focused on the field they were on when clicking Save. 

I believe that reRender of the Page will do the same thing.... loading the top of page. 

Any suggestions on how to retain the focus on the field contining the cursor. I'm almost thinking we will need to use a save method on the extended controller but prefer to keep things simple. 
Neetu_BansalNeetu_Bansal
Hi Rick,

In this case, reRender will resolve your problem and the page will not load. You can do some javascript coding, to put the focus to next field. I can help you on that. But for this I need the credentials, you can contact me either on my Gmail Id: neetu.bansal.5@gmail.com or Skype Id: neetu.bansal.5

Thanks,
Neetu
Rick MacGuiganRick MacGuigan
Adding ReRender of the page still loads the page to the top if I am in a field mid-way down the page. What advantage does rerendering provide in this case ?
Rick MacGuiganRick MacGuigan
Here's my extended controller. Wondering how to capture the field with an active cursor prior to Save then return the page referece page to that field focus ? 
 
public with sharing class AuditCommAutoPolicySampleController {

/*
This code supports the PROD_Commercial_Auto_PolicySample visualforce page.
FUNCTION:
New record Receives parent ID (accID) passed via commandbutton or custom button on parent related list.
AccId must be passed via URL since we are instantiating a new object reccord which is not saved.
accID is needed to query parent fields that are used on the visualforce page for rendering.
A list object is used for the SOQL query to the parent.  
The parent ID is loaded into the related list field on the instantiated object to establish relationship when saved. 
Note: 
//ApexPages.addMessages (plural) accepts only an exception. ApexPages.addMessage (singular) accepts a Message object 
*/
    //Protected Members
    private final ApexPages.StandardController stdController;  // corrected spelling of stdContoller
    private final string auditIdPrefix;

    //Properties
    public boolean IsNew {get;set;}

    public Comm_Auto_Audit_Sample_Policy__c AuditCommercialAutoPolicySample {get;set;}
    public Audit__c Audit {get;set;}

    //Constructors
    public AuditCommAutoPolicySampleController(ApexPages.StandardController controller) {
        try {
            stdController = controller;
            
            //Init Properties
            this.AuditCommercialAutoPolicySample =  (Comm_Auto_Audit_Sample_Policy__c)controller.getRecord();  
            this.Audit = new Audit__c();
            this.IsNew = (this.AuditCommercialAutoPolicySample.Id == null);


            //Get Audit Id Prefix

            Schema.DescribeSObjectResult dsr = Audit__c.sObjectType.getDescribe();
            this.auditIdPrefix = dsr.getKeyPrefix();   // Compile Error: Class static variable cannot be accessed via object instance at line 26 column 13 
            
            //Get Audit Id
            Id auditId = this.AuditCommercialAutoPolicySample.Audit__c;
                
            if (auditId == null) {
                string param1 = ApexPages.currentPage().getParameters().get('AccId');
                
                if (isAuditId(param1)) {
                    auditId = param1;
                }
                else {              
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Invalid Audit Id. Please contact the help desk with this error'));
                }
                 
            }

            //Load Audit Record
            List<Audit__c> audits = queryAudits(auditId);
            if (audits.isEmpty() == true) {
            
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'No records were found. Please contact the help desk with this error'));                          
    
            }
            else if (audits.size() > 1) {
            
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'More than 1 record found. Please contact the help desk with this error'));
            
            }
            else {
                this.Audit = audits[0];
                this.AuditCommercialAutoPolicySample.Audit__c = this.Audit.Id;
                if (this.IsNew) {
                    //Load defaults from audit template only for new samples.
                    //Keep for future reference on commercial auto audit. Used in personal auto. 
                    //this.AuditCommercialAutoPolicySample.Insured_State_Location__c = this.Audit.Default_Insured_State__c;
                    //this.AuditCommercialAutoPolicySample.Default_Liability_Limits__c = this.Audit.Minimum_BI_Limits_Only__c;
                    //this.AuditCommercialAutoPolicySample.Other_Liability_Limit__c = this.Audit.Other_Minimum_BI_Limits_Only__c;
                    
                }
               
            }
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }
    }

    //Public Methods



    //save and return user back to the audit .

    public PageReference saveAndReturn() {
        PageReference pageRef = null;
                
        try {
            PageReference saveRef = stdController.save();
            if (saveRef != null) { 
                    pageRef = new PageReference('/' + this.Audit.Id);
                    pageRef.getParameters().put('inline','0');
                    pageRef.setRedirect(true);
            }
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }

        return pageRef;
    }
    
    
    //just return user back to the audit .

    public PageReference ReturnMe() {
        PageReference pageRef = null;
        
        try {              
              pageRef = new PageReference('/' + this.Audit.Id);
              pageRef.getParameters().put('inline','0'); 
              pageRef.setRedirect(true);            
        }
        catch (Exception ex) {
            ApexPages.addMessages(ex);
        }

        return pageRef;
    }

   
    //Private Methods
    private boolean isAuditId(string value) {
        boolean isValid = false;

        if (value != null && value.length() >= 15 && value.length() <= 18) {
            isValid = value.startsWith(auditIdPrefix);
        }

        return isValid;
    }

    private List<Audit__c> queryAudits(Id auditId) {
        List<Audit__c> audits = new List<Audit__c>();

        if (auditId != null) {
            audits = [SELECT 
                        Id
                        , Name
                        , Policy_Information__c
                        , Policy_Number__c
                        , Prior_Carrier__c
                        , Expiring_Premium__c
                        , Reinstatement_Information__c
                        , Insured_Location__c
                        , Agent_Information__c
                        , Agent_City__c
                        , Agent_Name__c
                        , Driver_Information__c
                        , Age__c
                        , Gender__c
                        , Marital_Status__c
                        , Named_Insured_Add_Driver__c
                        , Occupation__c
                        , Business_Use__c
                        , Vehicle_Information__c
                        , Model_Year__c
                        , Vehicle_Type__c
                        , ISO_Symbol__c
                        , Annual_Miles__c
                        , Limit_Information__c
                        , Liability_Limits__c
                        , UM_Limits__c
                        , UIM_Limits__c
                        , UM_UIM_Limits__c
                        , PIP_Limits__c
                        , PIP_Deductible__c
                        , APD_Deductible_Vehicle__c
                        , Premium__c
                        , Rating_Information__c
                        , MVR_Violations__c
                        , Policy_Discounts__c
                        , Rating_Tier__c
                        , Credit_Scoring__c
                        , Telematics_UBI__c
                        , Loss_Information__c
                        , CLUE_Report__c
                        , Prior_Carrier_Loss_Experience__c
                        , Company_Loss_Experience__c
                        , Individual_Loss_Detail__c
                        , General_Information__c
                        , Signed_Application__c
                        , Vehicle_Photo_Information__c
                        , Proof_of_Ownership__c
                        , Other_Policies__c
                        , UW_Guidelines_Followed__c
                        , Risk_Management_Standards__c
                        , Personal_Auto_Product__c
                        , Default_Insured_State__c
                        , Minimum_BI_Limits_Only__c
                        , Other_Minimum_BI_Limits_Only__c
                        , MGA_Name__c
                        , Insured_Name__c
                        , Effective_Date__c
                        , Policy_Term__c
                        , Insureds_Primary_Location__c
                        , Other_Garaging_Locations__c
                        , Agent_Commission__c
                        , MCS_90_Endorsement__c
                        , Signed_UM_UIM_Rejection__c
                        , Other_Lines_of_Business_Written__c
                        , SIR__c
                        , Thirty_Day_Policy_Issuance__c
                        , Symbols_Appropriate__c
                        , Comprehensive__c
                        , Collision__c
                        , Type_of_Operations__c
                        , Type_of_Goods_Hauled__c
                        , Type_of_Service__c
                        , Radius_of_Operations__c
                        , Operating_Environment__c
                        , Unit_Count_by_Vehicle_Type__c
                        , Number_of_Drivers__c
                        , Driver_List_Updated__c
                        , Driver_Information_in_File__c
                        , Driver_Surcharge__c                        
                        , Court_Documents__c
                        , Excluded_Drivers__c
                        , Loss_Activity__c
                        , Inspection_Report_in_File__c
                        , Third_Party_CAB_SAFER_Other__c
                        , Company_Financials_Reviewed__c
                        , IRPM_Worksheet_Questions__c
                        , Questions_Posed_of_Agent__c
                        , Underwriting_Checklist__c
                        , Facultative_Reinsurance__c
                        , Properly_Classified_Rated__c
                        , File_Comments__c
                        , Operations__c
                        , Limits_Deductibles_Premium__c
                        , Audio_Video__c
                                                
                              
                FROM 
                    Audit__c 
                WHERE 
                    Id = :auditId];
        }

        return audits;
    }
}

 
Pramodh KumarPramodh Kumar

Here is the small Example to store the element id when mouse over and focusing after the Add method is completed.

Please let me know if you need any other help.
 
<apex:page standardController="account">
    <script src="/soap/ajax/30.0/connection.js" type="text/javascript"></script>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" />
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" />
    <script>
        var fileldId;
    	function oncfoucs(){
            debugger;
           fileldId = $(document.activeElement); 
        }
    function focusComplete(){
        fileldId.focus();
    }
    </script>
    <apex:form id="page">
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Add" onmouseover="oncfoucs();" oncomplete="focusComplete();"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection id="allthesets">
        	<apex:inputField value="{!Account.name}"/>
            <apex:inputField value="{!Account.active__c}"/>
            <apex:inputField value="{!Account.fax}"/>
            <apex:inputField value="{!Account.website}"/>
            <apex:inputField value="{!Account.rating}"/>
            
        </apex:pageBlockSection>
    </apex:pageBlock></apex:form>
</apex:page>


Thanks,
Pramodh.
 
Rick MacGuiganRick MacGuigan
Thanks for your response and code snippet Pramodh. Couple questions.
The oncomplete action is uniues to the Visualforce commandButton, correct ? I did not see any jscript recference to it. How does the oncomplete="focusComplete();" keep the field refrence if the page is reloaded ? Doesn't it loose the refference to the field ? 

Also, why are you pulling in the following?

<script src="/soap/ajax/30.0/connection.js" type="text/javascript"></script>
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" />
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" />

 
Rick MacGuiganRick MacGuigan
I also have juery 2.1.1 loaded in my org as a static resource. Is this what you are doing with the above statements ? In my case I would not need to specify the src since it is already loaded in the org , correct ? In that case can I do this :
 
<apex:page standardController="account">

    <script  type="text/javascript">
        var fileldId;
    	function oncfoucs(){
            debugger;
           fileldId = $(document.activeElement); 
        }
    function focusComplete(){
        fileldId.focus();
    }
    </script>

    <apex:form id="page">
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Add" onmouseover="oncfoucs();" oncomplete="focusComplete();"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection id="allthesets">
        	<apex:inputField value="{!Account.name}"/>
            <apex:inputField value="{!Account.active__c}"/>
            <apex:inputField value="{!Account.fax}"/>
            <apex:inputField value="{!Account.website}"/>
            <apex:inputField value="{!Account.rating}"/>
            
        </apex:pageBlockSection>
    </apex:pageBlock></apex:form>
</apex:page>

 
Pramodh KumarPramodh Kumar
Yes oncomplete is an attribute for some of the visual force tags to call javascript functions there are two functions in the script section. oncfocus() stores the previous id value when cursor changes or whenever you move the mouse and focuscomplete is used to get the focus back to the field once the save method is completely done. Use the static resource file stored in org. it will work
Pramodh KumarPramodh Kumar
Here is the information about include script for the javascript
https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_connecting.htm
Rick MacGuiganRick MacGuigan

I placed the following code but the page still loads to the top and does not move down to the field I was on 'Service_Operation__c' in this case. Even if I declare all SOAP request .

 

<script src="/soap/ajax/30.0/connection.js" type="text/javascript"></script>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" />
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" />
    <script>
        var fileldId;
        function oncfoucs(){
            debugger;
           fileldId = $(document.activeElement); 
        }
    function focusComplete(){
        fileldId.focus();
    }
    </script>
	
............
	
<apex:outputPanel style="text-align:center" layout="block">
<apex:commandButton styleClass="myClass" action="{!save}" value="Save Only" />
<apex:commandButton styleClass="myClass" action="{!saveAndReturn}" value="Save and Return to Template" />
<apex:commandButton styleClass="myClass" action="{!ReturnMe}" value="Audit Template Screen" />
<apex:commandButton styleClass="myClass" action="{!save}" value="Save Test" onmouseover="oncfoucs();" oncomplete="focusComplete();" />

</apex:outputPanel>
     
</apex:pageBlockSection>

............

<apex:outputPanel id="ajaxrequest2">

<!-- OPERATIONS  -->

<!-- <apex:pageBlockSection columns="1" id="section2" title="Operations" rendered="{!RatingInformation=true}"> -->
<apex:pageBlockSection columns="1" id="section2" title="Operations" rendered="{!Operations}" >

<apex:actionRegion >
<apex:pageBlockSection columns="1" showHeader="false"  >
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c}" id="operation" rendered="{!TypeOfOperations}" > 
    <apex:actionSupport event="onchange" reRender="typeOperation" />
    </apex:inputField> 
</apex:pageBlockSection> 
</apex:actionRegion>     

<apex:outputPanel id="typeOperation">    
<apex:pageBlockSection columns="1" showHeader="false" rendered="{!TypeOfOperations}" >  
<apex:inputField value="{!Comm_Auto_Audit_Sample_Policy__c.Service_Operation__c}" rendered="{!Comm_Auto_Audit_Sample_Policy__c.Type_of_Operations__c='Service' && TypeOfService}" />


 

 

 


 

 

Alex Skempris9Alex Skempris9
Any luck on this Rick? Did you manage to bring the focus to the field before the save? I'm having the exact same issue.

Thanks
Alex
Rick MacGuiganRick MacGuigan
@Alexios I did not. Our users seem ok with the way its working so I dropped this. Still would be nice to do but since the page makes a round trip to the cloud and back it seems to work more as a refresh after the save. 
Shauna HollandShauna Holland
We could currently use a solution to keep pages from reloading to the top after saving.   I do know that if you use control + S to save after modifying a cell using the pencil, the page does not reload to the top.  But in sections of the page where you must utilize  the "Edit" menu from the dropdown,  whether you hit the save button or you use control + S to save, the page reloads to the top,