How to Set Query

Good day, am trying to set a query to a field that is in Dialog but my code returns an Error please help, below is my code

let show_dialog = function (frm, fields) {
	let d = new frappe.ui.Dialog({
		title: "Details",
		fields: fields,
		primary_action_label: "Make Payment",
		primary_action: async function(values) {
			if (frm.is_dirty()) {
				await frm.save();
			}
		},
	});
    d.set_query("sales_invoice", function() {
        return {
            "filters": {
                "parent": frm.doc.name
            }
        };
    });
	d.show();
};

If I’m not mistaken you can add the get_query property directly to the field.

const fields = [
  {
    fieldtype: "Link",
    options: "...",
    get_query() {
        return {
            "filters": {
                "parent": frm.doc.name,
            },
        };
    },
  }
]

Hey @corentin thank you very much may God bless you. This has worked for me.

1 Like

Is there a way to set a query during runtime though?
In @imbra’s question, the filter is a constant (doc.name) and so can be set during creation using get_query. Suppose I want to set the filter based on another field in the dialog:

let d = new frappe.ui.Dialog({
    fields: [
        { fieldname: "item_code", fieldtype: "Link", options: "Item", reqd: 1 },
        { fieldname: "bom", fieldtype: "Link", options: "Item", reqd: 1 },
    ]
});
//how do I do the part below?
d.item_code.onchange = function (event) {
    d.set_query('bom', ()=>{
        return {
            'filters': { item: d.item_code }
        }
    })
}

Hello, it’s not a constant! Indeed it’s evaluated for every search, that’s why get_query is a function, so that the Link field can update the query on every keystroke.

const dialog = new frappe.ui.Dialog({
  fields: [
    { fieldname: "item_code", fieldtype: "Link", options: "Item", reqd: 1 },
    {
      fieldname: "bom",
      fieldtype: "Link",
      options: "Item",
      reqd: 1,
      get_query() {
        console.log(dialog.get_value("item_code"));
        return {
          filters: {
            item: dialog.get_value("item_code"),
          },
        };
      }
    },
  ],
});
dialog.show();

Hi @corentin, thanks! I was able to figure it out.
I am not super familiar with JS, so at the time, I didn’t know you could refer to the dialog from within it’s own fields dict at the time of creation. Hence my confusion.

const dialog = new frappe.ui.Dialog({
  fields: [
    { fieldname: "item_code", fieldtype: "Link", options: "Item", reqd: 1 },
    {
      fieldname: "bom",
      fieldtype: "Link",
      options: "Item",
      reqd: 1,
      get_query() {
        return {
          filters: {
            // I didn't know you could refer to "dialog" here
            item: dialog.get_value("item_code"),
          },
        };
      }
    },
  ],
});