Documentation

The best way to learn how to use the component is to use the Demo to see what options are available and then reference the source code in the examples folder to understand how it’s implemented. It’s also a good idea to skim through the methods and properties in the ASDoc file (as the demo doesn’t use every property/method available). Here are the two files: AutoComplete and AdvancedAutoComplete.

Although the component doesn’t extend from the ComboBox class, it’s designed to have as similar an interface as possible. For example, it implements the filterFunction, labelFunction and selectedItems properties as well as others.

Here’s the simplest possible implementation of the component.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application 
	xmlns:mx="http://www.adobe.com/2006/mxml" 
	xmlns:components="com.hillelcoren.components.*">
	
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			
			[Bindable]
			private var _data:ArrayCollection = new ArrayCollection( ["one", "two", "three"] );
			
		]]>
	</mx:Script>
	
	<components:AutoComplete dataProvider="{ _data }" />
	
</mx:Application>

While there are a fair number of settings you can adjust, I’d like to start by the showing the way I generally use the component.

<components:AutoComplete dataProvider="{ _data }" 
	prompt="Please select" backspaceAction="remove" 
	selectedItemStyleName="underline"/>

I’ve set three properties which I’ll review quickly here.

  • selectedItemStyleName: Controls the look of the selected items. There are four choices: macMail, facebook, underline and none.
  • prompt: A string to display when no value is set.
  • backSpaceAction: Determines what to do when a user clicks backspace. By default we focus the item (ala Mac Mail) but this can be changed to remove it.

Working with the data

Like most other Flex components you can set either the labelField or labelFunction property. By default this will control how the item is displayed through out the component (in the drop down, once selected and in the browsers).

You have a couple of choices for customizing the drop down label. You can define a dropDownLabelFunction which returns an HTML string to handle formatting the item. This is used in the email demo to display the person’s email address (ie, “Homer Simpson “) in the drop down. If you’d like greater control you can set a dropDownItemRenderer. This can be seen in the Color Chooser demo.

If multiple selection is enabled the component can contain both selected items and a search string. Because of this I’ve need to add a searchText property which can be used to get/set the search string. The text property returns a string representation of the selected items.

Related to this there are two main events which the component dispatches: change and searchChange. The change event is dispatched when the selectedItem property changes, while the searchChange event is dispatched when the search string is changed.

To filter the data you can either use the built in options by setting the “matchType” property or create a custom filter by setting a value for the “filterFunction” property. The built in options are:

  • beginning: Only match the beginning of the string.
  • word: Match the beginning of any of the words in the string.
  • anyPart: Matches any part of the string.

All of the built in options perform a case-insensitive search. Here’s how you could use the filterFunction property to implement a case-sensisitve search.

<mx:Script>
	<![CDATA[
		import com.hillelcoren.utils.StringUtils;
		import mx.collections.ArrayCollection;
			
		[Bindable]
		private var _data:ArrayCollection = new ArrayCollection( ["ONE", "TWO", "THREE"] );
			
		private function filterFunction( item:String, searchStr:String ):Boolean
		{
			return searchStr == item.substr( 0, searchStr.length );
		}
			
	]]>
</mx:Script>
	
<components:AutoComplete dataProvider="{ _data }" filterFunction="filterFunction"/>

To select items you have three options, you can use either selectedItem, selectedItems or selectedItemId. The first two options are pretty standard so I won’t cover them here. Setting the selectedItemId property will cause the component to search the items in the dataProvider for an object with a matching id. By default, it looks for a field called “id” on the item but you can set a custom field using the keyField property.

Out of the box the component requires the user to select an item from the list. You can allow the user to enter their own values by setting allowNewValues to true. You can then control whether or new the new items are editable by setting the allowEditingNewValues property. Additionally, you can set the allowDuplicates property to control whether or not to allow an item to be selected more than once.

A common question is how to use the component with data returned from the server. The best practice is to use a change listener. Once the user has entered enough characters fire off your data request. Once the data has been returned and passed to the dataProvider you can call the search() method to tell the component to filter the items and display the drop down. You can check out the DynamicData.mxml file in the examples folder to see the details.

You can use either an ArrayCollection or an XMLListCollection as the dataProvider. I showed you an example with an ArrayCollection earlier on, here’s an example using an XMLListCollection.

<mx:XML format="e4x" id="xml">  
	<items>  
		<item>one</item>  
		<item>two</item>
		<item>three</item>  
	</items>  
</mx:XML>  
	   
<mx:XMLListCollection id="xmlList" source="{ xml.item }"/>   	
<components:AutoComplete dataProvider="{ xmlList }"/>

Usability settings

Multiple Selection

This is the one feature which separates the component from other the AutoCompletes out there, setting the allowMultipleSelection to true enables the user to select more than one value. The AdvancedAutoComplete extends this feature by adding a selectionLayout property which when set to vertical causes the selected items to be displayed in a List component.

AutoSelect

The AutoSelect functionality will automatically select an item if it matches a case-insensitive string comparison and is the only match found. This feature can be disabled by setting autoSelectEnabled to false.

If you’d like to use a custom function to determine if an item should be auto-selected you can set a value for the autoSelectFunction property. Here’s an example where we use this property to auto-select once when there is a single match. For example, typing “o” will select “one” right away.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
			
		[Bindable]
		private var _data:ArrayCollection = new ArrayCollection( ["one", "two", "three"] );
			
		private function selectFunction( item:String, searchStr:String ):Boolean
		{
			return true;
		}
			
	]]>
</mx:Script>
	
<components:AutoComplete dataProvider="{ _data }" autoSelectFunction="selectFunction" />

Clear Icon

The core of the component is the PromptTextInput class. This class provides two main features: the prompt and the clear icon. We covered the prompt earlier but the clear icon is a little gray x icon which appears if there is text in the component. Note, this feature only works if allowMultipleSelection is set to false.

Drop Down

The number of items displayed in the drop down is controlled by the dropDownRowCount property. By default, the width of the drop down will
be set to match the width of the TextInput. However this can be overriden using the dropDownWidth property. On the topic of the drop down, you can use the showDropDown, hideDropDown and isDropDown visible to show/hide the drop down.

AdvancedAutoComplete

The challenge in building a component with lots of features is keeping it as streamlined as possible. In order to support adding more advanced functionality while not bloating the component I’ve created an AdvancedAutoComplete class which extends the AutoComplete component.

Selection Layout

As discussed earlier, setting the selectionLayout to vertical causes the items to be displayed in a List. When using the vertical layout you can use the showRemoveButton property to control whether or not to show a remove button.

Browsing

This can be enabled by either setting the showBrowseButton property to true, or by adding an options to the action menu (as is demonstrated in the Color Chooser Demo). By default we show a pop window which contains a searchable DataGrid. You can control which fields of the data to display in the grid using the browserFields property. If multiple selection is enabled, you can set the useListBuilder property to true to display a two column browser instead. If you’d like to implement your own browser you can either extends one the existing ones are create a component which implements the IBrowser interface. You’ll then need to set the browserClass property to your new class.

Ordering

If the selectionLayout is set to vertical you can enable the user to order the items in the list by setting the showOrderButtons property to true. If using the List Builder the ordering buttons will also be displayed in it.

Actions Menu

To enable the action menu you need to set a value for the actionsMenuDataProvider. This is just a regular Flex Menu component so all the usual features are supported (ie, using checkboxes). Here’s a link to the supported menu attributes. You can see an example of how to use this feature in the code for the AdvancedDemo. If enabled the menu can be displayed by pressing the down button while the component has focus.

Odds and Ends

Custom Skins

The selected items are simply buttons, this means it’s pretty easy to change the look and feel using skins. The styles which the component comes with (macMail, facebook, etc) are all implement using skins. It’s possible to define your own custom skin. If you’d like to implement it you can check out the CustomSkin.mxml file in the examples folder.

First Class Components

The component is made up of a number of classes. Some of these classes are useful in their own right. I consider the following three classes to be first class components:

  • PromptTextInput: This is a TextInput with two additional features, you can set a prompt which will appear when no value is set and a clear icon will appear when there is a value set and the mouse is over the component.
  • ListBuilder: This is a two column browser which can be used to add/remove items from a list.
  • CloseableTitleWindow: Adds a key listener to the TitleWindow which enables the user to click the ESC key to close it.

Utility Classes

The com/hillelcoren/utils folder contains a couple of helper classes. There are some useful functions here which you may be able to use elsewhere in your applications. Some examples include a function to compare if two ArrayCollections are equal and functions to convert string to/from camel caps.

Validating

You can use a regular validator to make sure that a value is selected. Here’s a simple example demonstrating how to implement it.

<mx:Validator source="{ autoComplete }" property="selectedItem"/> 
<components:AutoComplete id="autoComplete" dataProvider="{ _data }"/>

Inline Button

You can use the inlineButton property to set a button to appear at the end of the component. This feature is used in the AdvancedAutoComplete for the button used to display the actions menu. Here’s an example of how you can use this property to display a button which causes the drop down to appear (ala a regular ComboBox)

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;

		[Bindable]
		private var _data:ArrayCollection = new ArrayCollection( ["one","two","three"] );

		private function handleButtonClick():void
		{
			if (autoComplete.isDropDownVisible())
			{
				autoComplete.hideDropDown();
			}
			else
			{
				autoComplete.search();
				autoComplete.showDropDown();
			}
		}

	]]>
</mx:Script>

<components:AdvancedAutoComplete id="autoComplete" dataProvider="{ _data }">
	<components:inlineButton>
		<mx:Button skin="mx.skins.halo.ComboBoxArrowSkin" click="handleButtonClick()"/>
	</components:inlineButton>
</components:AdvancedAutoComplete>

That about does it, hopefully you found this useful. I plan to continue to improve the documentation over time. If anything here is unclear, or if there are other areas you’d like me to cover please post a comment and I’ll update the page.

Best,
Hillel

544 thoughts on “Documentation”

  1. when you try to add a new tag and want to name it “star”. but have already “starfish” registered as tag. it automatically selects this one instead of creating a new one. Is there a key or separator to avoid automatic selection? thanks for this excellent component, Hillel !

    1. Could you please provides some more details, are you setting a custom delimiter or are using the default (commas). Also, what about it exactly isn’t working.

  2. Hi Hillel,

    Thanks for the prompt reply, instead of the default delimiter which is a comma, I was ask to change it into semi-colon so I set the value of the delimiter property of the AutoComplete component into a semi-colon ( ; ) but it did not work. It still uses the comma. By the way thank you for sharing this great component it really helps me a lot in most of my projects.

    1. You’re absolutely correct, I’ll include a fix for this in the next version. For now to fix it you’ll need to use the source and replace the comma in line 61 of classes/IconButton.mxml in the commitProperties function.

      1. Thank you very much for this quick solution. Good thing I also have the source file. Have nice day Hillel. 🙂

  3. How can I change the sort order of items in the popup browser?

    I have:
    Room 1
    Room 2
    ….
    Room 9
    Room 10
    Room 11

    But – they display alphabetically, I want them to display in the natural order of the list.

    1. You’ll need to apply a custom sort function to your dataProvider. In order to sort numerically you’ll need to remove the “Room ” part of the string and then convert the remaining characters to numbers.

  4. Hi, Hillel! Once again, thank you for great component!

    I am facing a small problem.
    When I create custom skin for selected item, and then try to use it like this:
    selectedItemStyleName=”autoCompleteSelectedItemSkin”
    Compiler geves me an error:
    “Invalid value: autoCompleteSelectedItemSkin. It must be one of macMail, facebook, underline, none.”
    Flex SDK 4.5.1.

    Can you please give me some advice?

    1. I’ve managed to ovrriede the default style by adding by adding the same style name in my main application css file, that solved the problem.

  5. This component is awesome! Thanks for sharing!
    I have only 1 question – how can you preselect an item (I mean, let’s say this autocomplete is a part of a contact form and I want to use the form to edit the data taken from the db – the user hits edit button, and the contact form appears with all fields populated and ready for editing. How do I ‘tell’ the component to preselect one specific dataprovider (ArrayCollection) item?

      1. forgot to mention that I’ve already tried that, but I might be doing something wrong – could you provide an example of what should be there instead of “(the item you want to select)”. I have an array collection called citiesAC with ID and City in it (data taken from sqlite) – could you tell me how it should look like if I wanted to have any item preselected e.g. pair ID=2 and City=”London” ?

      2. Hi Hillel,
        I have 1 more question – how do I retvieve the selected item’s id after i ‘manually’ (using code) preselect some item. For example, I have an ArrayCollection citiesAC with 2 fields ID and City and i do:
        autoComplete.dataProvider = citiesAC;
        autoComplete.selectedItem = “London”

        and then when I do:
        trace(autoComplete.selectedItemID)
        i always get NaN instead of 2 as assigned in the Array Collection. Any ideas how can I retrieve the ID after I manually set the selectedItem property to any string?

      3. unfortunatelly it didn’t help. When I was debugging the app i saw that after calling validateNow() the only thing that changed was selectedItem and _selectedItem. SelecteditemId with no changes. Got any other ideas?

      4. Unfortunatelly that didn’t work neither. Anyway I did a little workaround to solve this – I searched the dataProvider manually comparing it to the city I wanted to preselect and then setting the actual autoComplete field using the selectedItemId that was assigned to the found item and everything works perfect.
        Maybe a thing to consider in future releases of the component would be automatic browsing thru the dataprovider to find the corresponding ID to a preselected item using String (for example autoComplete.selectedItem = “London”). That would make things easier a bit i think.
        Anyway thanks for your help! Cheers!

  6. Hi Hallel,

    I have doubt related to Auto complete…

    i have tow auto complete text box ( say book name and author)

    Book name ( ABC) selected from listing (ABC,DER,FEB) and author (BEL) also selected from authors listing(DEL,BEL,KAL)…

    When I focus the third textBox, popup should appear with the listing (ABC,BEL) of above text box answers…

    Can you please provide me a sample source code…

  7. Hi Hillel
    How can I set the fontFamily of the AutoComplete prompt?
    I went through the Documentation with no luck
    can you please assist?
    cheers
    🙂

  8. Hi Hillel and thank you for replying so soon 🙂
    I’m using flex 3
    so yes, of course I set the fontFamily style, and indeed it is working
    for the input text when I’m typing in it
    though when I focus out, the prompt is rendered in some other system font with Italic fontStyle…
    does the AutoComplete component uses two different text components for the prompt and the textInput?
    cheers
    Yariv

    1. The text input and the prompt are the same component. The class is called PromptTextInput and it should use the same font for the prompt just italicized. If you don’t want the font to be in italics you’ll need to use the source and modify it. The italics are set in the showPrompt function.

  9. Been reading through your documentation and although it is very helpful, just wanted to point out that the your coding examples are being HTML encoded making it very hard to read through the code quickly. Hopefully this can be remedied to make it easier for users of your components to read through your documentation.

    1. Thanks for pointing that out. I host my blog on wordpress.com and in the past they’ve changed how they display code. I’ve fixed the code examples in the documentation.

  10. I am more of a hobbyist Flex developer and I was able to get my basic needs to work without too much bother. Great component!

    I have AutoComplete running in a TitleWindow pop-up. Presently upon CHANGE, I call a local function that in turn directly calls a public function on the parent document. That works.

    But I would prefer to create an event listener in the parent document that listens for CHANGE in the pop-up and then calls the private function. However, I do not know which event listener to use – seemingly spark.events.IndexChangeEvent is not supported:

    popup[“autoComplete”].addEventListener(IndexChangeEvent.CHANGE, function)

    Thanks…

  11. Hi Hillel,

    First, Thank you for sharing this wonderfull component.

    Second, I just have an issue when I manully add the object to the AutoComplete upon its creation completion finished by using the autoComplete.addItem(myObject);
    And then when i try to use the Back Arrow button to delete that object, it didn’t do anything.
    If I selected another item form the dropdown list, and use the Back Arrow again, I got this error:

    RangeError: Index ‘1’ specified is out of bounds.
    at mx.collections::ListCollectionView/removeItemAt()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\collections\ListCollectionView.as:592]
    at com.hillelcoren.components::AutoComplete/handleKeyDown()[C:\Users\hillel\code\autocomplete\src\com\hillelcoren\components\AutoComplete.mxml:785]

    Can you help??

    Thanks,

  12. Hi Hillel .. I am using your great component. Running into a little issue whereby when I select an item in the autocomplete field .. it narrows down the list of items I show in a grid. I have to go to the next autocomplete field type a few spaces and then backspace to get it to access the autocomplete field.

    Any thoughts on how to control this?

    1. I’m sorry, I’m not clear on your implementation. Are you using it as in ItemEditor for a DataGrid? You may want to check out the source code for the demo in the examples folder as it demonstrates the best practice when using it with a grid. If that doesn’t help, if you could create a sample application which demonstrates the issue I’d be happy to help debug it.

  13. Hi, I would like to use your component in very restrictive UI. I haven’t found a way to NOT have the Inputbox grow vertically. Is it possible that the textinput behaves like a textinput (scrolls to the right if we have more characters than space). Thanks in advance. Benny

      1. Hi, thanks for the prompt reply! I don’t know if I am that apt to recode / override the FlexBox. I think the FlowBox concept just doesn’t fit with what I try to achieve. I will dig a little further to understand the AutoComplete code you wrote, mybe I can “dumb” it down that much that it just adds comma seperated text with the autocompleted values in a TextInput. Keep up the great work!!!

  14. Hi, awesome component, how can I expand the dropdown on creationComplete? so the first elements are visible. Thanks for your help

      1. Thank you… worked, also used the isDropDownVisible() to hide and show when I need to.

  15. 2 suggestions.

    1. Please add events FocusIn and FocusOut
    2. Please add styles to remove the focus indicator (focusThickness)

    1. 1. The events are there, they’re just hidden. If you type it, it’ll work.
      2. You can probably accomplish this by styling autoComplete.flowBox

      Best

  16. Hi,
    I’v used the AdvancedAutoComplete for two years now, and I think it is fantastic!
    However, up till now I used a local database for the dataProvider. Now I want to use a server side script to get a filtered set for the dataProvider. And I have no idea how to do that! I’ve looked at DynamicData.mxml, but I don’t see how I can accomplish anything (by the way, when I try DynamicData, nothing happens).

    I would be very greatful if you could help me on my way!

    1. DynaimicData.mxml demonstrates how to handle the UI, you’ll need to add a remote service of some sort to load the data though. The basic idea is that after the user types a couple of characters you search for the data on the server and add it to the AutoComplete’s data provider. If there’s a specific step you’re stuck I’m happy to try to help more.

      1. Thanks for your reply!

        I have a RemoteObject to get a dataset from the server, with an eventlistener to set the dataProvider of the AdvancedAutocomplete (aac). The getData method of the remoteObject is fired on the creationComplete event of the autocomplete. This works just fine.

        However, when I change this to get the data, not on creationComplete but on the change event of the AdvancedAutoComplete, nothing happens.

        In the onResult of the RemoteObject method I have:

        data = new ArrayCollection(e.result as Array);
        aac.dataProvider = data;
        aac.search();

        What am I doing wrong here?

      2. You probably want to use the searchChange event rather than the change event. The change event is dispatched when the selected item is change whereas the searchChange event is dispatched when the user changes the search string.

  17. Ha! That did the trick. Thank you!

    One final question: in the AdvancedAutoComplete, how can I listen for a click on one of the items in the list of selected items?
    By the way, I use your autocomplete in a course Ancient Greek, with a function that changes normal keyboard input on the fly in polytonic Greek. It works like a charm and teachers and students are very happy with it. One minor thing: I seem not to be able to use embedded fonts in the ShorterTextInput. Any explanation for this?

    1. The component doesn’t currently provide an easy way to listen to clicks on individual items, however I actually needed that feature in the current application I’m working on. To implement it I used the source code and modified the handleClick function in SelectedItem.mxml to dispatch an event. I’m sorry, I’m not sure why the embedded fonts aren’t working though.

      1. No sir! Not with autoComplete.setFocus() on applicationComplete, nor with this.setFocus() on creationComplete in ShorterTextInput.mxml. Perhaps I’m overlooking the simple solution? I have tried to find it in your source code (after all, the textinput receives focus directly after browsing…) but I have to confess that there is much in there I don’t understand. I can only hope that my questions aren’t too silly…..

  18. Thank you again! I will try out the InternalInterface, but I have already solved the problem without it:

    body onLoad = “setSWFFocus()”

    function setSWFFocus() {
    var myApp = document.getElementById(“${application}”);
    myApp.tabIndex = 0;
    myApp.focus();
    }
    and in the app of course creationComplete=”autoComplete.setFocus()”

    Also set params.wmode to “opaque” (for Chrome).

    Your AdvancedAutocomplete gives me many, many complex possibilities for exercises and quizzing. It is just great! If only I could find out how to make the list of selected items clickable, life would be perfect……. Actionscript is soooo much more difficult than Javascript!

  19. Hi Hillel,
    Great work on a much needed component!

    Q: I have allowMultipleSelection, allowNewValues and allowEditingNewValues all true. (Am really liking this combination… it provides a lot of features in a small form-factor. Nice!). Sure enough, the user enters a new value (“aardvark”) and selects a couple matches (“baboon”, “chicken”). The new one appears as plain text and the matching ones are nicely styled (am using “facebook”). So far so good.
    The user leaves and comes back. I really want to reproduce where he left off, with both new and matching values, appearing exactly as above. So I set selectedItems to an ArrayCollection with the previously supplied values. Unfortunately, the new values among them always appear as blanks (e.g. there’s a space long enough for ‘aardvark’, but it’s blank; ‘baboon’ and ‘chicken’ show up just fine in “facebook” style.) Note that when I inspect .selectedItems or .text, all 3 items are present).

    Any ideas on how to make ‘aardvark’ appear? (FWIW, I’m using Flex 4.6).
    Thanks!

    1. I think I see the problem, you’ll need to use the source and change the addItem function in AutoComplete.mxml.

      Change editableItem.height = textInput.height;
      to editableItem.height = 22;

      textInput.height is set to 0 which explains why you see the length of the text but not the height

  20. Hi,

    At this moment I’m using the autocompete for inserting items in a database and verifying that I create no doubles.
    I encountered a problem: once I have typed a word that is already on the list, I cannot insert a longer word that is an extension of the first. For instance, if I have the word ‘consul’ in the list, I cannot insert ‘consulatus’, for the shorter word gets immediately selected.
    Is there a way to solve this?

  21. Hello,

    Just a quick question, is there a way to remove text indent of the prompt text? I tried setting the value of textIndent and paddingLeft property to 0 but it doesn’t seem to work.

    Thank you in advance for the help.

    1. It’s not actually the text indent, rather it’s a very narrow TextInput which is used to capture text if the user wants to add a new selection by typing to the left of the selected item. You could try modifying the source to hide the component, it’s the ShorterTextInput at the bottom of SelectedItem.mxml.

  22. Hi,

    Thanks for your reply.

    And yes, autoselectenabled=false does prevent entering single words. However, when I want to insert a sentence with one or more comma’s, it keeps entering the unfinished sentence on typing the comma. Is there a way around this? Or is this just one more stupid question…..?
    I wish I could look for a solution myself, but I wouldn’t know where to look.

    1. Try setting the delimiter property, the default value is a comma which would explain your issue.

      The best way to look for solutions is to reference the documentation page as well as the ASDoc files (which are linked to at the top of the documentation page). If you can’t find the answer though I”m happy to try to answer your questions.

      1. Thanks for your kind reply. I am really at a loss here. Up to now I’ve worked with permanent data collections. Now that I’m trying to do the same with dynamic data I have trouble understanding what goes wrong and where. So here’s another question:

        When I get the data first (the full data collection), all goes well. But now I use the autoComplete.change event to get a selection based on the searchText. However, in the change eventhandler function the autoComplete.searchText appears to be an empty string (which gives me the full data collection instead of a selection) and the call search() does NOT show the dropdown list.
        What am I doing wrong here?

  23. Thanks again.

    Using the searchChange event did the trick for my autoComplete, but …… the searchChangeHandler of my ADVANCEDAutoComplete (next view state) fires spontaneously on Application start!!!!!

    1. Hmm… it’s possible it’s a bug with the component. You may need to modify the source to make sure the event isn’t dispatched until the component is fully initialized. A simpler solution may be to figure out a way to ignore the event. Sorry, I realize this isn’t the most helpful response.

  24. Hello,

    First of all thank you for this component.

    I’m kind of new to flex and all its wonder so excuse me if my questions are strange or hard to understand (some times I have a hard time understanding them myself).

    I’m trying to do “another kind” of auto complete then the ones in your examples. In my project we are trying to do a auto complete that should work as the ones in developing programs (ex Eclipse, Netbeans, Flash Builder, ect). I have a set of objects that has attributes (ex object1 has attributes x and y => object1.x and object1.y and object2 has attributes w and h => object2.w and object2.h). I use these objects and its attributes as variables to write formulas (ex object1.x + object2.w).

    So to my questions:

    1. I need the auto complete to be two levels. The second level of auto complete should depend on which object is selected on the first level. Is this possible? I have experimented with the showDropDown functions but haven’t really worked it out. Any help or an example where some one else has done it would help a lot. I saw in a comment that someone else were trying to do something similar but didn’t find any actual solution.

    2. In my TextInput I need to allow characters between the auto complete variables (ex 1.3 * object1.x + 0.5*object2.w ) to make it simple I need the auto complete to “start” when I write an character(a-Z). I’m having problems with this if you could give me a hint on how to solve it would help me a lot because now I’m all lost.

    Thank you again and I hope to hear from you.

    1. First off… welcome to Flex 🙂

      I’m sorry, but I’m not sure how well my component is going to suit your needs, this is pretty far removed from its standard behavior. If I was tasked with creating your app I don’t think I would use it. A simpler approach may be to use a standard TextArea component and add the required logic/dropDowns/etc.

      If after reading this you’re still not convinced, here are some pointers…

      1. The items shown in the AutoComplete are really just Button with the toggle property set to true (this can be seen in the SelectedItem class). You should be able to loop the FlowBox’s children to determine which item is selected.

      2. You could try listening to the searchChange event (which fires when the user enters text) and adding some custom logic. Alternatively, you may be able to dynamically change the filterFunction. You could selectively make it so that no matches are found which in theory should turn on/off the AutoComplete.

      Hope this helps

      1. Thank you for the answer,

        This is what I was afraid of. But I have learned a lot by reading your code any how so I don’t believe it was all in vain. I’m afraid I’m a bit over my head by making this as my first component due to its complexity but hey if the boss tells me to do it I guess I have to 🙂

        I think I could use your auto complete if I only simplify my own demands. If I remove the first demand/question and have all the variables in the list of the auto complete the only thing I need to do is to trigger the dropdown at the right time and print out the results with the right format and at the right place I believe your component could match my wants.

        Well again thank you for the answer. I will give it another go and try my best. I will probably come back with more questions if i decide to do as described above.

        Regards,

      2. Yeah… that’s a pretty tall order for your first Flex component.

        Best of luck! Feel free to ask as many questions as you’d like.

      3. I think I’m advancing. I have gotten a two level auto complete.

        Right now I’m listening to the “change” event as you do in the color demo and just change the dataProvider and labelField to my second level auto complete and it seems to be working fine.

        The rule of my app is that you should never write only “obj1” you are supposed to write at least “obj1.x” so this works fine for me.. for now.

        The problem I’m having now is that I cant figure out WHERE you print out the text in the TextInput. I use the “none” skin and all the choice I make in the auto complete becomes a comma separated list. I want the choice to become plain text so I can send it through to my “formula caluclator”. I have handled in the searchChange event the when the auto complete is supposed to be started and not.

        Is there another way I can contact you, it seems kinda stupid if I have a lot of questions to spam your Documentations commentary field.

        Thank you again and regards,

      4. Glad to hear you’re making progress.

        The text (as well as the commas) are set in the addItem function in AutoComplete.mxml.

        Sure, my email is my full name at gmail.com (no dots or dashes).

  25. hello…
    I think you are feeling in a preposterous gap in otherwise excellent Flex SDK.
    I was surprised to find out that there was nothing for this out of the box.

    I have a problem with the component. I get the data out of sqlite and as it turns out, i get the data back in good old array. So, I convert the array into an ArrayCollection and set it as the DataProvider of the component. The same ArrayCollection is also set as DataProvider of another DataGrid.
    Now, when I type anything in the autocorrect component everything from the DataGrid disappears and there are no drop down suggestions…

    Do you know a good example with sqlite?

    thank you for your help

    greetings from Mannheim

    1. o, I got it now, I was missing the labelfield attribute!! everything seems to be awesome …. but “I’ll be back” … 😀

    2. Now i have a real problem.
      I have very simple setup, a component and a button to add it to the database. The task is to get provide suggestions, but if there are no suggestions then the click of the button should save the search string into the database. But the problem is, I can’t find the original search string anywhere. As soon as I click on the button (that is, the component loses focus) I lose the information in that was there…
      is there any way I get the original text?

      1. You’ll need to use the searchText property and make sure that clearSearchOnFocusOut is set to false. If this still doesn’t work please let me know.

  26. Hey,

    Is there a way to add a title for the drop-down list(such as an item that’s shown in all cases)?

    Thanks alot 🙂

    1. If I’m understanding you correctly, using an item renderer would give you complete control over how the items are displayed. I’d suggest checking out the source code for the ColorDemo in the examples folder of the zip file.

  27. Hello, congratulation for the component very usefull !
    I have just one problem, i don’t find how i can display the list with all proposition and not oblige to have one letter.

  28. Hi Hillel great flex autocomplete. I liked a lot. I have one question i fill my autocomplete with an arraycollection from the database and i put on my autocomplete control and it works great. But when i fill another arraycollection for the disabledItems property it doesn’t work the autocomplete let me insert the same duplicate value, but if i typed on the control its works ok. Could you help me please.

    I put one example of my arraycollection maybe it helps

    private var originalArrayCollection:ArrayCollection = new ArrayCollection([
    {0:”F891CEC8-219E-46D2-BD8E-733FB2B1F944″,value:”Lic. Humberto Olguin Subgerencia de Desarrollo”}]);

  29. Hi again Hillen my arraycollection is this

    private var originalArrayCollection:ArrayCollection = new ArrayCollection([
    {0:”F891CEC8-219E-46D2-BD8E-733FB2B1F944″,1:”Lic. Humberto Olguin Subgerencia de Desarrollo”}]);

    And I fill the same way for my dataprovider and disabledItems but it doesn’t work with the disabledItems.

    Please could you help me

    1. I believe the problem is that when checking the disasbledItems it looks for the same object reference (not simply an object with the same values). You can either make sure you use the same objects in both lists or override the checkIfUnavailable function in AutoComplete.mxml to compare the object values.

  30. I love this component but I can’t see to get it working in a DataGrid. I am sure it is something I am doing. First here is an example of the ArrayCollection I am using.

    var colors:ArrayCollection = new ArrayCollection(
    [
    { “name”:”Almond”},
    { “name”:”Aproicot”},
    { “name”:”Beaver”},
    { “name”:”Copper”}
    ]);

    Next I define the the component in the declaration section

    In the DataGrid I use the following DataGridColumn

    The colorByFunction looks like this:

    private function colorByFunction( item:Object, column:DataGridColumn ):String
    {
    trace(item)
    trace(item.name)
    return item;
    }

    In this case “item” is the XML file associated with the selectedItem of the DataGrid. It is creating a node called “name” which is a string called
    “[object, object]”.

    Where am I going wrong.

  31. Hi, Hillel,

    I’ve been using the autocomplete component with no problems, until now… I tried to put an autocomplete inside a TitleWindow popup, but when I do that, the component loses any style even the dropdown is transparent, the component works as expected, it’s only the format that is wrong. Any idea on why is this happening. I tried on the same project outside the popup and everything works perfect.

    Thank you.

    1. I haven’t heard of this issue before, is it possible that you have other styles in your application which are causing it. You may want to try manually includes the defaults.css style sheet. If you could create a sample demonstrating the issue I’d be happy to help debug it.

      1. Thanks for you reply,

        This is happening only on my new modular application, I’m getting also an error: Skin for * cannot be found every time I use a numericstepper and some other objects, so I tried to find the source of this error, and found that I had to add this to the compiler arguments: -keep-all-type-selectors with that the autocomplete worked again with every style except for the selectedItemStyleName, it shows as a regular button. Any idea?

  32. Hi Hillel,

    I have a ArrayCollection with 10000 elements, when I used the advancedAutocomplete the search with the 2 first characters are slow, my question is if is possible to begin to search from three characters.

    Thanks in advance

    Jose

  33. Hi Hillel,

    Thanks for the component and your time and energy in making it available freely. I hope you can help out with an issue I’ve encountered.

    I’ve used a previous version of your plugin for years with no issue, but using AutoComplete-1.2-Fx3.swc when you click on an item in the list it clears out the autocomplete textinput.

    Config options are as follows:

    enableClearIcon=”true”
    clearSearchOnFocusOut=”false”
    autoSelectEnabled=”false”
    id=”AutoCompleteID”
    dataProvider=”{dynamicArray}”
    labelField=”label”
    matchType=”anyPart”
    change=”onChange(event)”
    selectedItemStyleName=”underline”
    backspaceAction=”focus”
    searchChange=”onSearchChange(event)”
    creationComplete=”creationComplete(event)”

    dynamicArray is bound to an ArrayCollection that gets updated from a webservice response (webservice call happens via onSearchChange event)

    in my onChange handler, the selectedItem is the correct value from the dynamicArray but something is later clearing that out and selectedItem goes back to null.

    Any thoughts?
    tia

    1. Is it possible that dynamicArray is getting updated which is then clearing the selection? Otherwise, if you could put together a sample application which demonstrates the issue I’d be happy to help debug it.

  34. Hi Hillel,

    I am using AdvancedAutoComplete and had set the property allowMultipleSelection to “true” and selectionLayout to “vertical” where the selected items are added in a separate list. i ahve also added showRemoveButton to “true”. Please lt me know how to remove all the items which appears in a list at a time. (Unlike the Remove Button functionality which removes only the selected one). I need something like adding a ‘Clear” button which clears the list.

    1. One solution would be to add an additional button to your UI and have the click handler call autocomplete.clear().

      Let me know if this doesn’t work for you.

  35. Hi Hillel,

    Thanks for the great component.
    I want the user to restrict entering special characters,similar to restrict property in TextInput.

    Please help

    Thanks,
    prasanth

  36. Hi Hillel, this component is very useful and thanks for to share it.
    I have a question, is possible to limit number of elements chosen.
    E.g. from the list of 20 elements I can choose max 3 elements.
    thanks in advance

  37. Hi Hillel, I can’t find a way to apply a background color on the main container, which is the best approach to do this?

    1. autoComplete.flowBox.setStyle( “backgroundColor”, );
      autoComplete.textInput.setStyle( “backgroundColor”, );
      autoComplete.textInput.textInput.setStyle( “backgroundColor”, );

  38. Hi Hillel!

    First of all, as everyone said, you are the best! I really like what you did and i am using it, but there is a problem that i couldn’t solve;

    i added an event listener to my instance like this;

    protected function baslat(event:FlexEvent):void{
    acinst.addEventListener(Event.CHANGE, dlF);
    }

    than the handler function is;

    private function dlF(event:Event){
    Alert.show(“OK”);
    }

    but when i try to compile it, there is some errors appears :
    Description Resource Path Location Type 1046:

    and this:

    Description Resource Path Location Type Can not resolve a multiname reference unambiguously.

    How can i listen change event?

    Best regards.

  39. Is there a way to change the errorColor for the autocomplete component?
    If you set the errorColor property (and then set an errorString) it still maintains the default red color!

    1. These are the three sub-components you can work with to make this sort of change.

      autoComplete.flowBox
      autoComplete.textInput
      autoComplete.textInput.textInput

      Hope this helps…

      1. Setting the errorColor style property on all these 3 doesn’t make it work (it does but it’s broken. Only when you hover never the border of the component does the color change to the correct one that was set. If you hover with the mouse in the center of the object, it still has the wrong color in the error tip, the border color is correct). Im looking in the source at the moment w/ debugger to find out what is retaining the default color… so far no luck yet.

  40. hi,Hillel Coren, i’m using AutoComplete in the DataGrid itemEditor,AutoComplete ‘s dataProvider = new ArrayCollection([{“shortName”:”m”,”fullName”:”mike”,”address”:”LA”},{“shortName”:”k”,”fullName”:”kate”,”address”:”Hawaii “},{“shortName”:”a”,”fullName”:”aron”,”address”:”Atlanta “},{“shortName”:”j”,”fullName”:”jore”,”address”:”Nevada “}]);

    i want when i input shortName ,the dropDown shows the fullName, and the DataGrid’s column shows the address.

    how to solve it?

      1. You may be able to add a click listener and then check if the target is a SelectedItem. Otherwise you’d need to modify the source. In SelectedItem.mxml add a click listener to the button and dispatch a custom selectedItem clicked event which bubbles.

  41. Hi,

    Is it possible to make the auto complete component insensible to special characters, especially for accented characters ?

    We would like to be able to find something like “Flèche” while typing “Fleche” or even “Fléche”.

    Thanks in advance.
    Regards,

    1. There are two parts to solving this.

      – First, you’d need to implement a custom filter function. Here’s a comment which provides an example: http://hillelcoren.com/flex-autocomplete/comment-page-1/#comment-1143
      – The more challenging part is removing the accents. Actionscript doesn’t seem to have native support for this but I found this post which suggests it should be possible using regular expressions: http://www.actionscript.org/forums/showthread.php3?t=211442

      Hope this helps

      1. Hi Hillel,

        Thank you very much for your answer. I have finally succeeded in making the search matching special characters by doing this:

        private function filterFunction( item:Object, searchStr:String ):Boolean
        {
        var libelleLong:String = item.libelleLong;
        var replacedSearch:String = cleanStringFromSpecials(searchStr);
        var replacedLibelle:String = cleanStringFromSpecials(libelleLong);

        return replacedLibelle.toUpperCase().indexOf(replacedSearch.toUpperCase()) > -1;
        }

        private function cleanStringFromSpecials(str:String):String {
        var replacedStr:String = str.replace(/[éèêë]/gi, “e”);
        replacedStr = replacedStr.replace(/[ïî]/gi, “i”);
        replacedStr = replacedStr.replace(/[öô]/gi, “o”);
        replacedStr = replacedStr.replace(/[ùûü]/gi, “u”);
        replacedStr = replacedStr.replace(/[àâä]/gi, “a”);

        return replacedStr;
        }

        However, now, the matched string in the dropdownlist is not highlighted when the I type “Fleche” and the word “Flèche” is found (for example).

        I would like to use the current highlight style used by your component (in order to avoid using a static style, which could be modified in the future by a skin and not in my function), to make it highlights the words by using my own matching procedure. Is it possible ?

        I’m already checking the email demo where you have made your own dropdownlistlabel function, but I may have to override the StringUtils.highlightMatch() function. Is there any documentation about it ?

        Thanks in advance for your help.

        Best regards,
        Anthony

      2. Well, I have managed to do it. Here is an example: http://imgur.com/eAy3RjD

        And here are the functions used to do it (using my previous function to clean the special characters, that I should review with the example provided in your link):

        public function dropDownLabelFunction( item:Object ):String
        {
        var libelleLong:String = item.libelleLong;
        var searchStr:String = autoComplete.searchText;
        var returnStr:String = highlighMatch(libelleLong, searchStr);

        return returnStr;
        }

        private function highlighMatch(str:String, searchStr:String):String {

        var returnStr:String;

        var replacedSearch:String = cleanStringFromSpecials(searchStr);
        var replacedString:String = cleanStringFromSpecials(str);

        var index:int = replacedString.toUpperCase().indexOf(replacedSearch.toUpperCase());

        if (index > -1) {

        returnStr =
        str.substring(0, index) +
        ‘ + str.substr(index, searchStr.length) + ‘
        + str.substring(index + searchStr.length, str.length);
        } else {
        returnStr = str;
        }

        return returnStr;
        }

        Note: this will highlight only the first group of matching letters, but I don’t mind it.

        Thank you for your help in solving this issue.

        Regards,
        Anthony

      3. No problem! Thank you for having answered so fast and helped me so much. I would be glad if this solution could help someone else.

        By the way, the bold line in my previous reply is wrong. I meant:
        ‘[b][u]‘ + str.substr(index, searchStr.length) + ‘[/u][/b]‘ (where ‘[‘ is ‘<‘ and ‘]’ is ‘>’ to make the style in the suggested line of the dropdown list)

        Anthony

Leave a reply to Luis Cancel reply