Dynamic Field Lookup

Hi All, first posting here.

Wondering if anyone has coded an autocomplete lookup field in an Anvil form. I’m trying to recreate a smaller version of my main site and one functionality I need is a field in which a user starts typing in a client name and after a number of characters, the field displays a drop-down of possible clients (starting with whatever characters have been entered in the lookup field). In my main site, I use AJAX calling PHP and the PHP in turn hitting a database of my clients.

I’m thinking I have to noodle around with JavaScript, but just posing the question here in case it has been done already.

Thanks in advance.

Regards,
David

No javascript required for this.

You can use the change event of the text box to see how many characters are in the text box. Then, if you have enough characters, you can call a server function that will do the lookup and return the good candidates. Something like:

# on the form
def textbox_change(self, **event_args):
    if len(self.textbox.text) < 4:
        return
    choices = anvil.server.call('get_choices', self.textbox.text)

# on the server
@anvil.server.callable
def get_choices(txt):
    return [row['name'] for row in 
            app_tables.names.search(name=q.ilike(txt + '%'))[:20]]

At this point you have the choices, and you can put them somewhere.

I think Anvil only has a drop down, not a combo, so you either play with css to convert the native drop down into a combo (I think it is possible, but I have never tried), or you fake it by adding a repeating panel under the text box, or you can look at the autocomplete component in Anvil Extras (which I have never used (yet)).

Thanks for the suggestion, I’m still shifting gears into the Anvil/Python foray so bear with me for newbie questions. Since I only need a drop-down list, I think I might be okay with what we have. I can embed an id into the drop-down list value (ex. “CLIENT ABC (123000)”) and use that once selected.

Regards,
David

If you need also the id, then you could retrieve both names and ids, and use tuples in the dropdown, like this:

@anvil.server.callable
def get_choices(txt):
    return [(row['name'], row.get_id()) for row in 
            app_tables.names.search(name=q.ilike(txt + '%'))[:20]]

If you assign a list of strings to a drop down items, the selected value will be one of the strings.
If you assign a list of tuples (str, value), you see the str and it returns the value.

1 Like

For the UI component, I ended up using autocomplete in Anvil Extras and it works pretty well. @stefano.menci - Thanks for your example code as that helped a lot too.