Flex 4 AutoComplete

As the by-product of an enterprise project I have built an AutoComplete component in Flex 4.
Using the new Spark architecture component logic and appearance can be separated in a clean way.

The component was updated for Flash Builder release SDK.

Here is a demo app showing two ways of usage:

Click here to view source code and download project.

You can use the following properties to customize the component:

  • minChars – the number of caharcters typed by the user after which completion begins
  • prefixOnly – if true, only items where the beginning matches the typed text will be offered for completion
  • forceOpen – if true, list will pop-up when comp receives focus
  • requireSelection – if true, first match is always selected and filled into the TextInput if user presses Tab
  • dataProvider – allowed types are Array, ArrayCollection, XmlListCollection; can also be asigned dynamically, i.e. with the result of an asynchronous call
  • labelField, labelFunction – standard Flex labelField and labelFunction
  • returnField – set this if you want the component to fill a value different from labelField or labelFunciton
  • sortFunction – function for sorting matching items, default is alphabetically ascending
  • text – text of the input text
  • selectedItem – selectedItem of list; read and write,set to null to reset selection
  • selectedIndex – selectedIndex of list, read only

The component dispatches 3 custom events:

  • select – type:CustomEvent; dispatched when user selects a list item by mouse or pressing Enter; listen to this to detect selection made by user
  • enter – type:FlexEvent, enter event of the TextInput
  • change – type:TextOperationEvent, change event of the TextInput

The visual appearance is defined by the skin file AutoCompleteSkin.as. The skin consist of a TextInput and a List component placed in a PopUpAnchor.

    <s:PopUpAnchor id="popUp"  displayPopUp="false"
        top="0" bottom="0" left="0" right="0"
        popUpWidthMatchesAnchorWidth="true"
        popUpPosition="below" >

        <s:Group id="dropDown" minHeight="22" width="100%">

            <s:List id="list" width="100%" minWidth="22" />

        </s:Group>

    </s:PopUpAnchor>

    <s:TextInput id="inputTxt" left="0" right="0" top="0" bottom="0" />

The logic in AutoComplete works like this: when the user types in text that matches with any items in the list we pop up the list showing these items.
There is a little trick here – all keyboard events are dispatched by the TextInput but we need to be able to select items in the list with the cursor keys. What we do is to re-dispatch some keyboard events on the list:

    private function onKeyDown(event: KeyboardEvent) : void{

        if (popUp.displayPopUp){
            switch (event.keyCode){
                case Keyboard.UP:
                case Keyboard.DOWN:
                case Keyboard.END:
                case Keyboard.HOME:
                case Keyboard.PAGE_UP:
                case Keyboard.PAGE_DOWN:
                    inputTxt.selectRange(text.length, text.length)
                    list.dispatchEvent(event)
                    break;
                case Keyboard.ENTER:
                    acceptCompletion();
                    break;
                case Keyboard.TAB:
                    if (requireSelection)
                        acceptCompletion();
                    else
                        popUp.displayPopUp = false
                    break;
                case Keyboard.ESCAPE:
                    popUp.displayPopUp = false
                    break;
            }
        }
    }
This entry was posted in Flex and tagged , , , . Bookmark the permalink.

25 Responses to Flex 4 AutoComplete

  1. bruce says:

    Am I doing something wrong? I can not seem to use a .setFocus() on the autocomplete.

  2. admin says:

    To set focus programatically try autoComplete.inputTxt.setFocus(). I’ll correct the bug some time, thanks for telling.

  3. bruce says:

    and to turn OFF sorting? To have the items displayed in the order they are in the dataprovider? (and Ditto, please keep up the good work, very clean, very usable. you rock! We need more components for those of us who are NOT component builders but system builders!)

  4. admin says:

    Bruce, you have two options:

    • 1. define your own sort function that sorts according to item order in dataprovider (i.e. it does nothing), and assign it to the sortFunction property
    • 2. simply comment out the sorting of the data inside the comp, around line 165.
  5. Pingback: JabbyPanda?s travel to RIA world » AutoComplete component for Flex 4 that supports entered text highlighting

  6. Ranch says:

    Need help with flash builder premium.
    After migrating to flash builder component stop working normally, can’t move down or up with the arrows and mouse selection do not work.
    Compiler is asking for “openButton” parameter as required with metatag ‘[HostComponent("spark.components.DropDownList")]‘.

    Even after adding to AutoCompleteSkin.mxml:

    Compiler is setisfied but problem still exist:
    can’t move down or up with the arrows and mouse selection do not work

    please help!!

  7. admin says:

    I have upgraded to Flash Builder 4 release version. Download the source again.

  8. Zachery says:

    Is there any chance this will be made into an ItemRenderer as well? or has anyone done this? Putting it into a DataGrid causes issues.

  9. Ranch says:

    Thank you very much, after the upgrade it works fine as a stand alone.
    But, when the autocomplete is part of a datagrid the mouse down code is not working. any suggestion?

  10. Matthew Montana says:

    Great component. Clean and quick. Question…Would it be possible to add icons to the component, both in the text input and the pop up list?

  11. admin says:

    Yes, you need to edit the skin file AutoCompleteSkin – to change the input – and to define a custom item renderer for ListAutoComplete – to change the popup.

  12. Matthew Montana says:

    Any chance you could throw together a quick and dirty sample of adding icons? I’m very much a noob. I’m not sure where to even start modifying those files. Thanks in advance.

  13. Vicary Archangel says:

    It throws a RangeException when you press enter on every thing in the list is filtered out.

    You can fix this by adding “&& collection.length > 0″ in the first if statement under method acceptCompletion().

  14. Vicary Archangel says:

    A few fine tuning:
    1. on _focusOutHandler, clear out selectedIndex and selectedItem on “collection.length == 0″.
    2. on set selectedItem, also set _text rather than just inputTxt.text.
    3. Directly changing the dataProvider may cause filter and sorter already set being malfunctioned, shoulda create new ListCollectionView or something with the same source on setting dataProvider property.

    Great component and I’m sure I’ll use it for a long time.

  15. admin says:

    Thanks for the tips. I have implemented the first two and updated the source.
    I haven’t experienced no 3. so far.

  16. Shafi says:

    Thanks for sharing the code.

    If we have to dynamic dataProvider. When user press the “A” it should fetch the data from there server and show them in list

  17. cg says:

    Is there anyway to allow for free text as well as the dropdown list?

    For example, when using as in input field, as people type in the text box for a first name, they will see a list that help them pick a list of predefined common names, but they are still free to enter their own name. eg – “J” (shows John, Jenny, Jake) … “John” (only two items left in the list “John”, “Johno”)… user enters “Johnster” which might be their actual name and continues on with the rest of the form

  18. cg says:

    Ok, found out how to do this myself. Removed lines 321 – 324 in the Autocomplete.as file. The following lines where the item is being set to null

    if (collection.length==0){
    _selectedIndex = -1;
    selectedItem = null;
    }

  19. Pingback: Flex 4 Custom Component: Flow List with AutoComplete « …

  20. dk says:

    I guess it was as easy as setting prefixOnly property to “false”.

    Thank You

  21. Mary Jo says:

    Thanks for the nice autocomplete component, works just as I was looking for! However, I’m having one issue with it. When I put my autocomplete textfields inside a mx:FormItem with a label, the label gets pushed to the top. Whereas the normal textfield labels in the same form are properly aligned to the middle of the field. Any idea what would cause this or how to fix it?

  22. Mary Jo says:

    Also, please consider adding tabIndex as an attribute for the field, it does not currently handle this and is very important for accessibility (and just nice to have on larger forms).

  23. Michele says:

    Hi,
    i’m working with your component. I see a stange behaviour: in the components:AutoComplete id=”ac1″ i changed requireSelection=”false” and then i entered some values. If i entered value that doesn’t match dataprovider when i leave component, combobox has null value (example if i input ‘ss’) , if i put a value (‘aa’) and the leave component: combobox is not null and contains ‘aa’ that doesn’t belong to dataprovider. Is there a way to change this ?
    Thank
    Michele

  24. admin says:

    I have just uploaded a fix for this bug. Thanks for telling.
    Ivan

  25. mansoor says:

    thanks alot sharing such a good component.
    I used it my project thanks again.ME HAPPY :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">