How to check if a doctype has checked field?

I have a doctype that has a check field type. And only one document can have this field ticked. So how to check if there is other document already ticked?
I think Unique attribute can’t be used because unticked would be considered as non-unique also, so invalidate saving.

I’m thinking that a solution would be in js. But I’m not a programmer so I don’t know the code. If anyone can share the code it would be great.
Thank you

As an example, let’s assume DocType is Customer, and the checkbox field is Disabled.

If you’re looking for JS code, you could do something like this:

frappe.db.get_list("Customer", {
  filters: { 'disabled': true},
  fields: ["name"] }
).then( (results) => {
  if (results.length > 1) {
   // If more than 1 result:
   console.log(`Number of Customers with checkbox 'Disabled' = ${results.length}`);

However, if your goal is to prevent this scenario from happening? I would not use JS. I would add some Python code to a controller method on the DocType, such as validate().

That way, the validation always happens. With or without the browser.


Similarly, in a Server Script:

if doc.enabled and frappe.db.get_value("Language", {"enabled": 1, "name": ("!=",}):
    frappe.throw("there can be only one enabled language")

(get_value returns the name of one existing doctype that matches the filters, if any (truthy), or None (falsy))

1 Like

Thanks @brian_pond
Thanks @rmeyer
I will try both to see which fits to my case.

Actually looking at your code, the term I missed was enabled and disabled. My mistake was using the check value (0, 1).
And my goal is just to display a warning when user click on a checkbox, hence the js.