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…