How to make autocomplete field load data dynamically from ajax?

I have this field

which produce this behaviour

ezgif.com-video-to-gif

I would like for an AJAX request to be triggered whenever a user types, which will replace the autocomplete option from the response that received from AJAX request.

How can implement this?

@asuramus
you can use the get_data method of the frappe.ui.form API.
add an onload function in your js that will make the autocomplete feild, below is the example code:

frappe.ui.form.on('FormName', {
    onload: function(frm) {
        // set up the autocomplete field
        frm.set_query('field_name', function() {
            return {
                query: 'path.to.ajax.call',
                filters: {
                    // add any filters you need
                }
            }
        });
    }
});

Change the FormName with the name of form where you need to add the autocomplete.

Thank you.

2 Likes

@VINOTH Thank you!!!

Hi @VINOTH, thank you for answering my question. I have tried the solution you provided and it works. However, when I add the filters, the filters did not appear in the request parameters.

I am missing something?

@asuramus
there are a few things you can check:

  1. Make sure that you are adding the filters to the correct field name. The set_query method should be called on the form object, and the first argument should be the name of the field you want to add the filter to.
  2. Make sure that the set_query method is being called after the form has finished loading. You should call the set_query method inside the refresh event of the form.

For example:

frappe.ui.form.on('FormType', {
    refresh: function(frm) {
        frm.set_query('field_name', function() {
            return {
                filters: {
                    'example_filter': 'example_value'
                }
            };
        });
    }
});

Thank you.

Ah, now I understand. So filters are only applied if the filter name exists in fields_dict. thank you again.

i think this work only for link field what about if fieldtype is Data, so how to show some values in that field.

If you want to make this process in the data field dynamically load information from the API or database, the method that you can use for here is frappe.ui.form.on

Example code:

frappe.ui.form.on('DocType', {
  refresh: function(frm) {
    // make an AJAX request to fetch the data
    frappe.call({
      method: 'myapp.api.get_my_data',
      args: {},
      callback: function(r) {
        // update the data field with the result
        frm.set_value('data_field', r.message);
      }
    });
  }
});

Info: API endpoints should only return a single value; they should not return any kind of list or dictionary because the set_value method is only for single values. If you are getting lots of data, you need to extract it and send it to the respective field response.

Thank you.