When to use hook event?

hi
i was thinking what is the best practices , when should i write a hook function to api file OR write inside the same doctype controller py
like event after_insert … should i handle it in hook or in doctype controller ?

1 Like

You should do it in the hook, you should never modify the ERP/Frappe doctype direclty. Otherwhise it will create issues later on.
You can create/uncomment in the hook.py those lines

doc_events = {
    'Customer': {
        'onload': [
            'your_app.events.on_project_after_save'
        ],
  },
}

When you want to execute something on an event, you should create a file called events.py at your_app/events.py, then write the method like this:

def on_project_after_save(doc, handler=None):
       #write what you want here

So the after_save you created will run and the after_save in the controller will run also. I don’t know if there’s a way to cancel the controller to execute…

1 Like

hi @mel_erp
thanks for the replay i appreciate it . my case is about custom doctype itself not related to customization ,
i start to work new project and saw the code structure … it has a lot of functions in the hook file i was thinking should i move them to their related doctype , or stick with hook.py .
is best practice to use hook to add event to erpnext and frappe with out changing them only ?
but in this example he could do it without hook

hook function to user validate

but he could use it def validate(self): the logic

when to write in hook and why not in controller if it’s a custom doctype not related to erpnext

1 Like

Hello dear friend

Have you find the best practice/way to use it?

I’m also on a custom doctype and wondering exactly the same

what i do for now .
1- if it’s related to erpnext/ frappe i use hook
2- if it’s related to my custom doctype i write it inside it’s controller
3- if the same function used in two or three custom doctypes on event , i use it in hook and so when i change it it apply everywhere so i don’t have to rewrite it in many places

3 Likes