Only run a method if a variable changes on Save

Hi all,

As the title says, I have to run some methods the cleanest way possible.

1 of them has to run before the doctype is saved and im using before_save, works well. But once the doctype is saved, and a field is changed somewhere else, once the user presses save the same method runs again. I only want the method to run once (on initial creation) and never again.

secondly, Is there a way to run a method only if it changes after saving? currently if you use the {fieldname} Triggered when the value of fieldname is changed
every time the field is clicked/unclick the method runs, but I only want it to run after the save is clicked and if the value actually changed.
Any help is greatly appreciated.
Thanks

Hi there,

Would the before_insert hook suit your needs? That’s only called when the doc is first created.

Are you looking for a client-side or server-side method? On the client side, I’m not able to reproduce this. The {fieldname} hooks only trigger for me when the value is changed, not when the field is clicked.

If you’re trying to do this server-side, could you use doc.get_doc_before_save()?
https://frappeframework.com/docs/v14/user/en/api/document#docget_doc_before_save

thanks for getting back so quick.
Absolutely, thanks Ill use the hook!

In regards to the second point, the method called is server side.
For example, when the Customer Doctype has the Primary address field changed I dont want anything to trigger there and then. If its changed and the button save is pressed, then check if the value is different and call the method. If its saved and the value is the same dont run the method. The method is running even before the save button is clicked. Here is the code:

Thanks

Your best bet then would be to trigger your remote call in an on_save event, not a {fieldname} event. Check to see if the value has changed using doc.get_doc_before_save(), and only make your remote call if it has.

Also, if you’re looking to maintain data integrity, I’d consider making this a server script rather than a client script. A lot can go wrong on the client side that your application wouldn’t be aware of.

Hi Peterg,
Thats what I did in the end.
All works like a charm, thanks for the help!

1 Like