Hooks doc_events on a dynamic list of doctypes

I have a list of DocTypes for which I need to configure common behavior via doc_events (after_insert, on_submit, …).

The list of DocTypes is not static, it is dynamic and may contains some user added custom doctypes.

Right now I configured the events on “*” within the hooks.py, and I validate within each events if the current DocType is part of the list of DocTypes to process.

This is working, but I don’t like having “*” events being triggered for ALL doctypes.

So instead of using hooks.py, I would like to manually update the dictionnary map of doc_events that frappe is holding in memory/cache.

Any insights how to do this ?

Hi @guimorin,

Particular doctype doc_event method call for apply it like:

# Syntax
doc_events = {
  "Your DocType": {
      "on_update": "your_method_with_proper_path"

# Example
doc_events = {
  "Lead": {
      "on_update": "method.testcall"

Thank You!

The doctypes are known only at runtime, they come from a database query.

I kind of assumed I couldn’t code much in the hooks.py file, but it turns out I could do the following right after the assignation of doc_events variable, which perfectly solve my situation.

    def _set_doctype_event(doctype_dict, event, value):
        if not isinstance(doctype_dict[event], list):
            doctype_dict[event] = [doctype_dict[event]]

    doctypes = frappe.db.sql("<some select returning the doctypes>",pluck=True)
    for doctype in doctypes:
        doctype_dict = doc_events.setdefault(doctype,{})
        _set_doctype_event(doctype_dict, "after_insert", "...my_events.after_insert")
        _set_doctype_event(doctype_dict, "on_submit", "...my_events.on_submit")
        _set_doctype_event(doctype_dict, "on_cancel", "...my_events.on_cancel")
        _set_doctype_event(doctype_dict, "on_trash", "...my_events.on_trash")