Dynamic options for autocomplete field

Dear community,

I’m trying to setup dynamically an autocomplete field named label. My goal is to define the auto completion options to every labels previously recorded for the same doctype.

Here is my custom js script :

async function set_labels_suggestions(frm) {
  frappe.db.get_list(frm.doc.doctype, {
    fields: ['label'],
  }).then((records) => {
    if (records.length > 0){
      frm.set_df_property("label", "options", records.map((label) => label.label));
    }
    else
      frm.set_df_property("label", "options", []);
  });
}

Unfortunately, that does not work. Which is very strange by the way, is that with another fieldtype (e.g Selection), that works perfectly (all recorded labels are displayed).

Since the autocomplete field is not documented, can someone share his/her custom script for dynamic fetching of autocomplete fieldtype ?

Thank you in advance !
Antoine.

Hi @Antoine_Barrier,

Please apply and check it.

frappe.ui.form.on('Your DocType', {
  onload: function(frm) {
    set_labels_suggestions(frm);
  }
});
async function set_labels_suggestions(frm) {
  frappe.db.get_list(frm.doc.doctype, {
    fields: ['label'],
  }).then((records) => {
    if (records.length > 0) {
      const options = records.map((label) => ({ value: label.label, label: label.label }));
      frm.set_df_property("label", "options", options);
    } else {
      frm.set_df_property("label", "options", []);
    }
  });
}

Then reload and check it.

Thank You!

Hi @NCP and thank you for your answer !

Unfortunately, that does not work much. I suspect the autocomplete field have some extra behavior which fill the options field after my script…

Hi @Antoine_Barrier:

Try this:

frm.fields_dict.yourfield.set_data(["one", "two"])

Hope this helps.

3 Likes

Really sorry for answering so late, I paused the development for a while. I can now say that it works with your solution. Here is the complete method I’m using now :

async function set_labels_suggestions(frm) {
  frappe.db.get_list(frm.doc.doctype, {
    fields: ['label'],
  }).then((records) => {
    if (records.length > 0) {
      const options = records.map((label) => ({ value: label.label, label: label.label }));
      frm.fields_dict.label.set_data(options)
    } else {
      frm.set_df_property("label", "options", []);
    }
  });
}

With this :

frappe.ui.form.on("MyDoctype", {
  refresh: function (frm) {
    set_labels_suggestions(frm);
  },
}

Thank you very much for everyone who answered here ! :slight_smile:

How i can use this in child table

Did you find any answer

Noo, I am still finding how will we use autocomplete field inside of the child table