You need to sign in to do that
Don't have an account?
Visual Force Auto Complete Component ;)
Hello everyone, just wanted to share with the community this custom component I made and give something back for the help I've received. :smileyhappy:
The purpose of the component is to enable autocomplete in lookup fields. I used the autocomplete js created by Jim Roos:
(http://www.jimroos.com/2007/05/ajax-autocomplete.html) but made some modifications to it so that it could interact with an Apex controller among some other things...
So my idea was that if you were making a VF page that had an inputfield that was related to a lookupfield you would just insert this autocomplete component to that inputfield. Something like this:
The component has 4 parameters:
The name of the object or custom object that the inputfield relates to (new objects must be added inside the apex classes since i had some problems constructing a dynamic query).
The InputId which is used to relate the component to the input field
The id for the Component
A classname parameter that basically just defines the width of the suggestions menu.
Here's a screenshot of how it looks like in action:


Here's a link to the file containing the required files:
AutoCompleteComponent
Jonathan.
Message Edited by jonathan rico on 08-16-2008 01:55 PM
Message Edited by jonathan rico on 08-17-2008 09:04 AM
The purpose of the component is to enable autocomplete in lookup fields. I used the autocomplete js created by Jim Roos:
(http://www.jimroos.com/2007/05/ajax-autocomplete.html) but made some modifications to it so that it could interact with an Apex controller among some other things...
So my idea was that if you were making a VF page that had an inputfield that was related to a lookupfield you would just insert this autocomplete component to that inputfield. Something like this:
Code:
<apex:inputField value="{!Contact.accountid}" id="accname" styleClass="cField">
<c:autocomplete ObjectName="Accounts" InputId="{!$Component.accname}" AutoCompleteId="accACid" ClassName="autocomplete300"/>
</apex:inputField>
The component has 4 parameters:
The name of the object or custom object that the inputfield relates to (new objects must be added inside the apex classes since i had some problems constructing a dynamic query).
The InputId which is used to relate the component to the input field
The id for the Component
A classname parameter that basically just defines the width of the suggestions menu.
Here's a screenshot of how it looks like in action:


Here's a link to the file containing the required files:
AutoCompleteComponent
Message Edited by jonathan rico on 08-16-2008 01:55 PM
Message Edited by jonathan rico on 08-17-2008 09:04 AM
Hello everyone,
I just made a minor update to the component. I fixed an issue with IE freezing because of some JS issues. And also a small issue related to escaping single qoutes.
Autocomplete Component
Hope this solves problems for some of you.
cheers!
All Answers
Would you mind if we publish this to our open-source repository on code.google.com?
Thanks Ron.
Hi Jonathan,
This code is very useful for us. We tried it and loved it but it just has one small problem since the page gets saved whern you select any value from the suggestion list.
Do you know how to stop the page from being "Saved" or "Submitted" when the value is selected from the suggestion drop-down list.
Thanks and regards,
Ambili
Awesome, good to hear it's working for you. About the save issue.. you mean the page gets saved when you hit enter? or the tab key?
Thanks for your prompt reply.
The page does a "save" action when I use the arrow keys(down arrow) to select a value from the auto-complete drop-down list and when after I hit the "Enter" key to select the desired value. (I realised that this was the only way to select a value from the auto-complete list because the mouse-over select using the mouse was not working for some reason)
Basically we need the value from the dynamic auto-complete to be just populated in the text-field that has the auto-complete component enabled without having a Submit or Save action after selecting the value.
Do you know why this "Save" action might be happening after a value is selected using the enter key?
Also I noticed that the values cannot be selected using the mouse...and hence I had to user the down-arrow key.
We are using Internet explorer 6.0 and 7.0.
We greatly appreciate your valuable feedbacks on this.
Thanks and regards,
Ambili
This is a default action of VF pages, but I'll let you know if i find a workaround for this issue.
And for the mouse over event, i've just added some more javascript to detect the onmouse over event, i'll post the new version of the autocomplete as soon as i can.
I managed to find a solution for the page submit issue when "Enter" key is pressed.
Using JavaScript to prevent or trigger form submission when ENTER is hit<script type="text/javascript"> function noenter() { return !(window.event && window.event.keyCode == 13); } function enter(nextfield) { if(window.event && window.event.keyCode == 13) { nextfield.focus(); return false; } else return true; } function entsub(event,ourform) { if (event && event.which == 13) ourform.submit(); else return true;} </script>
input type="text"
tag(s) in your form:onkeypress="return noenter()"
Thanks and regards,
Ambili
Thank you.
Jonathan,
Do you know a way to have a custom lookup page display instead of the standard VF lookup page?
I would hire you to implement this if you have a solution.
Lance@StudioITinc.com
That almost worked for me. Instead, I have this function:
<script>
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
and then call onkeypress="return disableEnterKey(event)"
inside my <apex:inputField> tag(s).
Thanks!
Hi Johnathan,
Great post, has been a real help. One issue I have found it with getting the Auto Suggest function to work in data tables with columns. The lookup works, however the suggestions seem to get hidden behind the subsequent input field in the table.
I'm not that clued up on CSS / JavaScript so don't really know where to start looking, so if you could provide any guideance that would be a great help.
Code below:
<apex:page standardController="Contact" sidebar="false"> <script type="text/javascript" src="{!URLFOR($Resource.autocompletejs)}" /> <apex:stylesheet value="{!$Resource.autocompletecss}"/> <style> .cField{ width:300px; } </style> <script> function disableautocomplete() { var forms = document.getElementsByTagName('form'); for (var i = 0; i < forms.length; ++i) { if (forms[i].setAttribute) { forms[i].setAttribute('autocomplete', 'off') } else { forms[i].autocomplete = 'off' } } } if (window.addEventListener) { window.addEventListener('load', disableautocomplete, true) } else if (window.attachEvent) { window.attachEvent('onload', disableautocomplete) } else { window.onload = disableautocomplete } </script> <apex:sectionHeader title="Contacts AC Sample Page" subtitle="Select Account" /> <apex:form id="VFformid" > <apex:pageBlock title="Contact Edit"> <apex:pageBlockButtons > <apex:commandButton action="{!save}" value="Save" /> <apex:commandButton action="{!cancel}" value="Cancel"/> </apex:pageBlockButtons> <apex:pageBlockTable title="Information" columns="1" value="{!Contact}" var="con"> <apex:column> <apex:inputField value="{!Contact.lastname}"/> </apex:column> <apex:column> <apex:inputField value="{!Contact.firstname}" styleClass="cField"/> </apex:column> <apex:column> <apex:inputField value="{!Contact.accountid}" id="accname" styleClass="cField"> <c:autocomplete Width="300" ClassName="autocomplete" InputId="{!$Component.accname}" AutoCompleteId="accACid" ObjectName="Account" /> </apex:inputField> </apex:column> </apex:pageBlockTable > </apex:pageBlock> </apex:form> </apex:page>
Hi
Thanks for this componet ,I have used this component in one of my project.
But I have small issue in searching,if I put "a" it show me the result which contains character "a".
But I want my result should be starts with "a".
So how can I do this in this componet.
Please please help me out.
Thanks
Hi Mrutyunjay,
You will need to edit the stext variable in the Autocomplete Controller.
Change from this:
String stext = '%'+System.currentPageReference().getParameters().get('aname')+'%';
To this:
String stext = System.currentPageReference().getParameters().get('aname')+'%';
Removing the % from the front of the string ensures the wildcard matching starts after the value you enter as opposed to including the value you enter.
% is to SSQL / SQL what * is to file system searches.
e.g. Searching for files containing A would be: *A* and files starting with A would be: A*
Hope that helps.
Paul
Thank for this response.
I have done this lot of time but unfortunately this does not work in this code.I donot know this show "No result" always.
Can you please check this in your code please.
Hi Mrutyunjay,
I tested it before I posted my reply and it worked as expected, if you can post the code you are using perhaps we can see where it is failing.
Cheers
Paul
This is my code I am using for product lookup
public PageReference searchSuggestions() {
//Initalize variables, hasparams just indicates that a search has started
resultsname.clear();
hasparams = true;
hasnoresults = false;
//Obtain current parameters
String sobjectname = System.currentPageReference().getParameters().get('objectname');
String stext ='%'+ System.currentPageReference().getParameters().get('aname')+'%';
//Limit Suggestions to 10 Results
Integer iLimit = 10;
//Validate if there's an input and get results
if(stext.length() > 2){
try{
String sql = 'select name from ' + sobjectname + ' where name like \''+stext+'\' limit '+ iLimit;
for(sobject x : Database.query(sql)){
String s = (String)(x.get('name'));
resultsname.add(s);
}
}catch(Exception e){
resultsname.add('Unexpected Error, please contact support');
}
}
return null;
}
This is my VF page code
<apex:outputText >Products</apex:outputText>
<apex:panelGrid columns="2">
<apex:inputField value="{!SFDC_520_QuoteLine__c.Product2__c}" id="prdname" styleClass="cField">
<c:autocomplete Width="200" ClassName="autocomplete" InputId="{!$Component.prdname}" AutoCompleteId="Prductid" ObjectName="Product2" />
</apex:inputField>
Hi,
You code shows a % before and after the .get('aName') when assigning the sText variable. So that's your problem.
Paul
Hi All,
Can anybody help me how can i implement Filtered Lookup using this, Means one lookup value is filtered on the behalf of other lookup value selection ?
Hey guys,
Sorry I haven't visited this post in a while. Some of may have noticed that using this component in IE may freeze the browser, there's a problem with an onblur function in javascript that might be causing a loop. I'll update the new version with this fixed as soon as possible and let you know so you can download the newest version.
GauravKumar:
Do you have reference from one lookup to the other? This is an interesting case, a dependant autocomplete... If you have a way to reference the master lookup from the dependant lookup then you could try modifying the autocomplete component to recieve and id of the master lookup. Then on the onchange action of the masterlookup rerender the dependant autocomplete so that it contains the value of the new masterlookup.
Then you will need to modify the AutoCompleteController to filter entries by the id provided in the master lookup parameter..
Hope this helps you.
Hi
Yes Some has Refrence and some has not.
Yes i have modified My Controller Class and My Filtered Lookup works Fine in Case of Pre Selected Value and On Record Edit.But for e.g When I create New Record and suppose select any Account and then i will select Contact then Contact is not filtered on the befahlf of selected Account.
And In Edit Case Suppose Selected Account is "A" and Selecteec Contact is "C" then in Contact lookup in Auto Complete this will shows all contact which Account is "A". but when I Change "Account "A" to Account "B" then Contact lookup Auto Complete will not Showing result on the Behalf of Account "B" this is showing Previouse Contact list (All Contact which Account is "A").
Can Any Body help me how can i refresh values on on Lookup value selection.
First off, thank you for writing this app and making it available, it's awesome.
Now to my issue.....
I'm trying to get this to work inside of a repeat tag with no luck. The search box says "searching", but always returns an empty result set. I'm not seeing any javascript errors and I don't believe it's a unique ID situation because I'm using a list that only has 1 record in it. Has anyone else tried to get it working in a repeat tag, successful or otherwise?
Thanks!
Hey there,
Can you post your VF code?
Thanks Everybody for Reply.
I figure out my Problem now My AutoComplete Filtered Lookup is Working. :)
Thanks
Hello everyone,
I just made a minor update to the component. I fixed an issue with IE freezing because of some JS issues. And also a small issue related to escaping single qoutes.
Autocomplete Component
Hope this solves problems for some of you.
cheers!
How come when I try and save the component I get
Error: Literal value is required for attribute id in <apex:outputPanel> at line 20 column 30
yes, i'm having the same issue. Trying to figure out what changed..
I'll let you know as soon as I have a fix for this.
I had the same issue. You need to set the API version of the VF page and component to v15. It seems that after v15 sf.com changed something that stops the use of dynamic IDs.
Hope that helps.
Awesome thank you
but I get an error on my component
Literal value is required for attribute id in <apex:outputPanel> at line 20 column 30
???
Try changing the current API version of the component to 15.
<apiVersion>15.0</apiVersion>
Yeah, I forgot to put in the testmethods, I'll add them in the apex class as soon as I have a chance.
Another question... This is great for inputting data, but what happens if I created a controller, and I want to look up someone in a textbox, so that my report is dynamically created once the filter is in...
So something like
InputText = Type something (AutoComplete comes up)
I need an autocomplete for reporting purposes not inputting data... Is that possible with your tool?
So basically what you want is for the autocomplete component to come in place when a specific input is detected? If this is the case, what will the specific input define? The object on which the autocomplete filters on?
Hmm I think so... Basically I have a search box which is a reference field to this object.. So let say..
Contact input box and as soon as I type into the inputbox ... autocomplete does it magic and then I can have the user hit go and a report will show up based on that inputbox...
Can that happen?
Ah, so what you want is to launch a report with the selected autocomplete suggestion as a parameter so that your report can filter based on that parameter.
This is definitley possible, but you will need to customize the component.. You will need to modify the selection event so that it opens a new window with a report. You can send the name of the selected option as a criteria for the report using url parameters. The parameter pv0 refers to the first criteria parameter, pv1 to the second and so on..
so your url will look something like this:
http://YOURSFDCINSTANCE.salesforce.com/YOURREPORTID?pv0=AUTOCOMPLETESUGGESTIONID&pv1=OTHERCRITERIAFIELD
Now, if you need the ID of the selected option , then that's another story. This will require more customization on the controller side because you will need to have a mapping of Name to ID so that you can see the names as suggestions but when you click an option send the ID of the option as a paramter for the report.
Question about this autocomplete...
If i wanted the billingState to appear when they lookup an account with the accountname.. How would I do that.. I did add the BillingState to the component but do not see it appear..
For example:
when the user types in:
for an existing account which is autohonda and billing state is NY
so when the user types in auto
all of the auto autocomplete comes up that is great
but want
autohonda|NY
autocompl|NJ
the billing state will have no effect on the id itself just need it to appear....
Thanks
Hi Jonathan - Thanks for developing such a nice component.
Hi Sachinch
What is your issue?
Hi Jonathan - Please see my code below. What I get is no value selection from the drop down list. It looks like it is working in the background though.
<apex:page standardController="Account" sidebar="false">
<script type="text/javascript" src="{!URLFOR($Resource.autocompletejs)}" />
<apex:stylesheet value="{!$Resource.autocompletecss}"/>
<style>
.cField{
width:300px;
}
</style>
<script>
//This is a small workaround for getting the component to work with the enter key
//I'll include this behavior as part of the component in a next release
function noenter(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
function disableautocomplete() {
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; ++i) {
if (forms[i].setAttribute) {
forms[i].setAttribute('autocomplete', 'off')
} else {
forms[i].autocomplete = 'off'
}
}
}
if (window.addEventListener) {
window.addEventListener('load', disableautocomplete, true)
} else if (window.attachEvent) {
window.attachEvent('onload', disableautocomplete)
} else {
window.onload = disableautocomplete
}
</script>
<apex:sectionHeader title="Contacts AC Sample Page" subtitle="Select Account" />
<apex:form id="VFformid" >
<apex:pageBlock title="Hello {!$User.FirstName}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
<apex:pageBlock title="Programs">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:facet name="header">Contact Name</apex:facet>
<apex:column >
<apex:outputField value="{!contact.Name}"/>
</apex:column>
<apex:facet name="header">Reports To</apex:facet>
<apex:column >
<apex:inputField onkeypress="return noenter(event)" value="{!contact.reportsToId}" id="cname" styleClass="cField">
<c:autocomplete Width="300" ClassName="autocomplete" InputId="{!$Component.cname}" AutoCompleteId="accACid" ObjectName="User" />
</apex:inputField>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Hello,
I'm having trouble getting KeyEvents working under IE8. Specifically, KeyUp, KeyDown, Enter all aren't functioning.
Using the component for an InputText field and everything works fine minus KeyEvents on IE8. Firefox is working fine. DId some research and it seems certain IE8 does have issues supporting some Java KeyEvents.
Any help would be appreciated.
Hello,
We have a similar requirement to provide autocomplete control on custom vfp page. Few queries:
1) Is the code available for free and can be used for production? Any cost associated with it ? Where can I find the latest code? Please provide me the link or access to the latest code.
2) Is the control available for custom vfp pages too?
Hello,
I tested the component code as it is without doing any changes in firefox. However, I am getting no results on UI. It keeps on showing Searching...... I put some logs in the code and the result is showing values in getResultsname function. Please let me know what could be the reason of this. Am I missing anything?
Also, please respond to my earlier queries as to whether its possible with custom vfp pages?
Hi everyone, sorry for taking so long to answer to your questions.
Could you please give me more information about the API version you're using in your pages/controllers.
I'll try to reproduce the issue.
Regarding the previous questions. This code is free and you may use it in any vfpage.
One of the purposes of this component is to save some time for developers that face this requirement, so if you use it and you happen to find a bug please let the rest of us know( and if possible give a solution...) The same applies for any improvement to the code.
Hello Jonathen,
Thanks for the response.
I downloaded the code that is available on in one of your post here. Not sure if thats the latest. Can you please provide me the latest code.
Regarding the API version, my page, component and controller all are api version 18. The logs in background(server side) do show the data in getresultsname but the UI doesnt show up. I am testing on Firefox 3.6.3
Its a bit at priority for my project, so I would wait for your response eagerly.
I guess sachinch is also facing similar problem.
Thanks
Hey,
Have you tried changing the API version of the component to 15? The behavior of the ID attribute of the components changed after i published this component.
I need to figure out another way of setting a dynamic id for the components, untill I have an answer for this please try changing the API version of the component.
Let me know if this worked for you.
Hi Jonathen
Thanks for your quick response. I really appreciate that. Yeah I just tried changing the API version to 15 and setting the dynamic ID back to panel in component and it works fine. I opened up the post to sent you the finding but you have been too nice and fast in identifying the cause.
I will now implement it on my custom page. Thanks again!!
Hello ,
Thanks for this great piece of code jonathan.
I am trying to customize the query so that i can choose the field instead of name .
I have put in
and also added it to the query but keep getting Unexpected Error, please contact support as result! if I replace the +sobjectfield+ in the query and just replace name by test_autocomplete__c it just works fine.
The problem seem that i dont know how to assign the sobjectfield to the one define in the page.
and the component
I would be very grateful if you could help me out !
Jonathan,
Your AutoComplete component is great. I am trying to make a minor adjustment but am not very familiar with HTML and CSS. When the component displays the list of values, the background color behind the text is clear, thus it is difficult to see the values. In your original example, the background is a light blue and the seleted value is a darker blue. The non-opaque background helps see the possible values better than the opaque background. Can you tell me which CSS values need to be set for the background color and selected value in the CSS/Component please. Thanks.
Hi Jonathan - Thanks for developing such a nice component. It helped me out a lot.
But i am facing an issue i am creating a pageblocktable in which i am using an inputfield, so the field is repeating the number of elements in the list.
On click of textbox i am able to get the Data, but the textbox only displays seaching... i have rendered result directly on output panel and it displays the result but not able to view it on the dropdown with textbox. It displays ony searching...
Waiting for your response.
Thanks
Neha J
Hello
This is a great component
does anyone has the testmethod?
Hi Jonathan,
Great Post:)
The component is works only if you place single tag for component on Page. I tried to place 2 tag for component for two different lookup, then its not working.
Please correct if I am wrong.
Thanks for posting such a good component
Thanks
Gurpreet
Hello,
Am also facing the same problem while implementing this. if you find solution for this please reply.......i need solution for this.
"
Thanks for this componet ,I have used this component in one of my project.
But I have small issue in searching,if I put "a" it show me the result which contains character "a".
But I want my result should be starts with "a".
So how can I do this in this componet.
"
Thanks In Advance.
Hi,
The auto complete component doesnt working for product lookup please help on this. It is urgent for client. It is working for all except for product. Give any suggestion.
Thanks,
Krish
Hi,
I am using auto complete its working for all objects except product object. It is very urgent for client. please give me suggesion.
please find below my code:
<apex:inputField value="{!a.Product__c}" onkeypress="return noenter(event);" id="prod"><c:autoCompleteController objectname="Product2" additionalfield="TickerSymbol" autocomplete_textbox="{!$Component.prod}" /></apex:inputField>
thanks
krish
Hi,
how to use auto complete component for text box. please help me.
Thanks,
lakshmi.
I put this solution in my developer env. I am having 2 problem:
How to get ID of selected account in Autocomplete Component ???
Please do rply with example
Thanks
If you check the sample page file in the zip, it contains the following code.
<apex:inputField onkeypress="return noenter(event)" value="{!Contact.accountid}" id="accname" styleClass="cField">
<c:autocomplete Width="300" ClassName="autocomplete" InputId="{!$Component.accname}" AutoCompleteId="accACid" ObjectName="Account" />
</apex:inputField>
In this code Selected account is binded directly to the field {!Contact.accountid}.
Selected account id will be populated in to that field.
Hope thats helps!
Thanks Prasanna...but how to get that same id in apex in select query...I have done something like,
VF code :
<apex:pageBlockSection title="DataConsumer Relations" columns="1">
<apex:inputField onkeypress="return noenter(event)" value="{!DataConsumer__c.Name}" id="dcname" styleClass="cField">
<c:AutoComplete Width="300" ClassName="autocomplete" InputId="{!$Component.dcname}" AutoCompleteId="Name" ObjectName="DataConsumer__c" />
</apex:inputField>
</apex:pageBlockSection>
Apex code :
public Id SelectedDC {get; set;}
public string SelectedDCName {get; set;}
public PageReference DispDCData()
{
SelectedDC = [Select Id,Name from EBPExtentiaBI__DataConsumer__c where Name=: SelectedDCName limit 1 ].Id;
System.debug('dcname'+SelectedDC );
lstDCData = new List<DataFieldAndSources>();
if (SelectedDC == null)
{
return null;
}
List<EBPExtentiaBI__MapConsumerDataField__c> lstMCDF = [
select EBPExtentiaBI__DataField__c, DataField__r.EBPExtentiaBI__Name__c
from EBPExtentiaBI__MapConsumerDataField__c
where EBPExtentiaBI__DataConsumer__c =: SelectedDC order by id
];
lstDCData = getDataFieldsNSources(lstMCDF);
return null;
}
Please help ???
try this
<apex:inputField onkeypress="return noenter(event)" value="{!DataConsumer__c}" id="dcname" styleClass="cField">
<c:AutoComplete Width="300" ClassName="autocomplete" InputId="{!$Component.dcname}" AutoCompleteId="Name" ObjectName="DataConsumer__c" />
</apex:inputField>
lstMCDF = [
select EBPExtentiaBI__DataField__c, DataField__r.EBPExtentiaBI__Name__c
from EBPExtentiaBI__MapConsumerDataField__c
where EBPExtentiaBI__DataConsumer__c =:DataConsumer__c order by id
];
Hi Jonathan nice post.
I have a question. suppose on 'Test account 1' I have Phone field with value '3333'. I display 'Phone field' of contact on the page and i want to populate the 'Phone field' of contact with the Phone field of Account when the user clicks 'Test account 1'
How can i do this.
Thanks for posting such a useful component. I'm looking for the updated version of this component and the link that you had provided no longer exist. So could you kindly re-post the files
regards,
JAG
You can give a try to following components:
http://appexchange.salesforce.com/results?type=Apps&keywords=Auto%20complete
-Jag@SF
Hi,
I downloaded the zip file and try to save the component but it is saying
Error: Literal value is required for attribute id in <apex:outputPanel> in autoComplete at line 20 column 72
at line 20 i have <apex:outputPanel id="OP_{!AutoCompleteId}" layout="block" >.
what the error.how to rectify it..
Thanks,
Bujji
Am not able to download your AutoComplete Component.
could you please help i need autocomplete for a text box to search in a single object using SOSL .